简体   繁体   English

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

[英]How to Determine if ::before is applied to an element?

I have this simple html code.我有这个简单的 html 代码。 I need to be able to determine if the::before is being applied to.icon-player-flash我需要能够确定是否将 ::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>

在此处输入图像描述

I thought this would work but it's always returning 0 for the length.我认为这会起作用,但它总是返回 0 的长度。

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

What am I missing?我错过了什么?

Use getComputedStyle and check the value of content .使用getComputedStyle并检查content的值。 If it's none then the pseudo element isn't defined:如果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>

This property is used with the:before and:after pseudo-elements to generate content in a document.此属性与:before 和:after 伪元素一起使用以在文档中生成内容。 Values have the following meanings:值具有以下含义:

none没有任何

The pseudo-element is not generated .不生成伪元素。 ref参考

If you want to count simply consider a filter:如果您想计算,只需考虑一个过滤器:

 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM