如何确定 ::before 是否应用于元素?

Kat*_*udd 4 javascript css jquery

我有这个简单的 html 代码。我需要能够确定 ::before 是否应用于 .icon-player-flash

    <div id="TestSwitch">

        <i class="icon-player-html5"></i>

        <i class="icon-player-none"></i>

        <i class="icon-player-flash"></i>

    </div>
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述

我认为这会起作用,但它总是返回 0 长度。

var flashplayer = $(".icon-player-flash:before");
console.log("count: " + flashplayer.length);
Run Code Online (Sandbox Code Playgroud)

我缺少什么?

Tem*_*fif 5

使用getComputedStyle并检查 的值content。如果是none,则未定义伪元素:

var elem = document.querySelector(".box");
var c = window.getComputedStyle(elem,"before").getPropertyValue("content");
console.log(c);

var elem = document.querySelector(".alt");
var c = window.getComputedStyle(elem,"before").getPropertyValue("content");
console.log(c);
Run Code Online (Sandbox Code Playgroud)
.box:before {
  content:"I am defined"
}
Run Code Online (Sandbox Code Playgroud)
<div class="box"></div>

<div class="alt"></div>
Run Code Online (Sandbox Code Playgroud)

此属性与 :before 和 :after 伪元素一起使用以在文档中生成内容。值有以下含义:

没有任何

不生成伪元素。参考

如果你想计数,只需考虑一个过滤器:

const elems = document.querySelectorAll('div');
const divs = [...elems].filter(e => {
   var c = window.getComputedStyle(e,"before").getPropertyValue("content");
  return c != "none"
});

console.log(divs.length)
Run Code Online (Sandbox Code Playgroud)
.box:before {
  content:"I am defined"
}
Run Code Online (Sandbox Code Playgroud)
<div class="box"></div>
<div class="box alt"></div>

<div class="alt"></div>
<div ></div>
Run Code Online (Sandbox Code Playgroud)

  • `$(this).get(0);` &lt;= 实际上与 `1 + 1 - 1` 相同。您正在包装该元素,然后将其展开。 (2认同)