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)
我缺少什么?
使用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)
| 归档时间: |
|
| 查看次数: |
2168 次 |
| 最近记录: |