我有这个简单的 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>
我认为这会起作用,但它总是返回 0 长度。
var flashplayer = $(".icon-player-flash:before");
console.log("count: " + flashplayer.length);
我缺少什么?
Use 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);
.box:before {
content:"I am defined"
}
<div class="box"></div>
<div class="alt"></div>
此属性与 :before 和 :after 伪元素一起使用以在文档中生成内容。值有以下含义:
none
The pseudo-element is not generated. ref https://www.w3.org/TR/CSS22/generate.html#content
如果你想计数,只需考虑一个过滤器:
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)
.box:before {
content:"I am defined"
}
<div class="box"></div>
<div class="box alt"></div>
<div class="alt"></div>
<div ></div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)