简体   繁体   English

如何使用 jQuery 检查 CSS 中是否存在类

[英]How to check if a class exists in CSS with jQuery

I have class .hello in css:我在 css 中有.hello类:

<style>
    .hello { color:#ccc }
</style>

How can use Jquery to check class .hello exist in style or not?如何使用 Jquery 检查类.hello存在样式?
Of course, it need to check all style even in <link href='style.css' /> document.当然,即使在<link href='style.css' />文件中也需要检查所有的样式。

Following will check if certain styles are applied to the element (doesn't absolutely confirms that whether it came from stylesheet) 下面将检查某些样式是否应用于元素(并不是绝对确认它是否来自样式表)

if ($('.hello').css('color') == '#CCC') {
   // true
} else {
   // false
}

First specify the external file you want to search an existing class then try to replace whitespaces to "" if string "gap" was found is greater than 0 then class "gap" is found. 首先指定要搜索现有类的外部文件,然后尝试将空格替换为“”,如果找到字符串“gap”大于0则找到类“gap”。

  (function($){
            jQuery.get('assets/css/main.css', function(data) {
                var str = data.replace('n','');
                if(str.match(/gap/g).length>0) {
                    console.log('class was found!');
                }else{
                    console.log('no class!');
                }
            });       
        }) (jQuery);

You can use getComputedStyle() for element to get the styles. 您可以使用getComputedStyle() for element来获取样式。

Color is obtained as rgba and is converted to hex with the logic here 颜色以rgba获得,并在此处使用逻辑转换为十六进制

 $('.hello').each((i, el) => { if (rgb2hex(getComputedStyle(el).color) == "#cccccc") { console.log('#cccccc el => ', el); } }); function rgb2hex(rgb) { rgb = rgb.match(/^rgb\\((\\d+),\\s*(\\d+),\\s*(\\d+)\\)$/); return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); } function hex(x) { let hexDigits = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"); return isNaN(x) ? "00" : hexDigits[(x - x % 16) / 16] + hexDigits[x % 16]; } 
 .hello { color: #cccccc; } 
 <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script> <div class="hello"> hello </div> <div class="hi"> hi </div> 

See below code snippet, the function returns the found class or id from the stylesheet or from style tag we pass. 请参阅下面的代码片段,该函数从样式表或我们传递的样式标记返回找到的类或id。 And returns an empty string if not found. 如果找不到,则返回一个空字符串。

<script type="text/javascript">
function getDefinedCss(s){
    if(!document.styleSheets) return '';
    if(typeof s== 'string') s= RegExp('\\b'+s+'\\b','i'); // IE 
capitalizes html selectors

    var A, S, DS= document.styleSheets, n= DS.length, SA= [];
    while(n){
        S= DS[--n];
        A= (S.rules)? S.rules: S.cssRules;
            for(var i= 0, L= A.length; i<L; i++){
           tem= A[i].selectorText? [A[i].selectorText, 
A[i].style.cssText]: [A[i]+''];
            if(s.test(tem[0])) SA[SA.length]= tem;
        }
    }
    return SA.join('\n\n');
}
       console.log(getDefinedCss ('ui-helper-hidden'));

                  </script>

Let me know if it works for you. 请让我知道这对你有没有用。

Simpler still..还是更简单。。

if($('.<class name>').length <= 0)
{
// load style sheet
$('<link href="style sheet ULR" rel="stylesheet">').appendTo("head");   
}

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

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