如何确定:: before是否应用于元素? [英] How to Determine if ::before is applied to an element?

查看:80
本文介绍了如何确定:: before是否应用于元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this simple html code. I need to be able to determine if the ::before is being applied to .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.

I thought this would work but it's always returning 0 for the length.

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

我想念什么?

推荐答案

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

Use getComputedStyle and check the value of content. If it's none then the pseudo element isn't defined:

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伪元素一起使用以在文档中生成内容.值具有以下含义:

This property is used with the :before and :after pseudo-elements to generate content in a document. Values have the following meanings:

未生成伪元素 . 参考

The pseudo-element is not generated. ref

如果要计数:

console.log($('div').filter(function( ) {
    var elem = $(this).get(0);
    var c = window.getComputedStyle(elem,"before").getPropertyValue("content");
    return c != "none";
  }).length);

.box:before {
  content:"I am defined"
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>
<div class="box alt"></div>

<div class="alt"></div>
<div ></div>

这篇关于如何确定:: before是否应用于元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆