将类添加到具有特定CSS属性的元素 [英] Add Class To Elements With Specific CSS Property

查看:119
本文介绍了将类添加到具有特定CSS属性的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个脚本,该脚本将迭代"body"下的每个元素,并将检查其"background-color".如果此背景色与'#eb2c33'相匹配,则脚本将向该元素添加一个类,否则它将移至下一个元素. 我这样做是为了避免进入html并将该类手动放入元素. 这是我的代码.

I am creating a script that'll iterate each element under 'body' and will check for its 'background-color'. If this background color matches to '#eb2c33', then the script will add a class to that element or else it'll move to the next element. I am using this so to avoid going into the html and put that class to elements manually. Here is my code.

$(document).ready(function (e) {
        
  $('body *').each(function(index) {
    
         var rgbg = $(this).css('background-color');
         if(rgbg == "#eb2c33")
         {
                $(this).addClass('jcbg');
             
              }

      });
});

现在,如果我在诸如header或footer等的特定div上进行迭代,则此函数将完美工作.但是,当我在整个DOM上进行迭代时,此函数将无法使用. 请注意,我使用的csshook会为我提供十六进制的颜色值,而不是rgb,所以请不要这样做.有帮助吗?

Now, this function works perfectly if i iterative over a specific div like header or footer etc. But when i iterate over the whole DOM, this function is not working at all. Please note that i am using a csshook that'll give me color values in Hex rather than rgb so please don't go for that. Any help?

更新:

我现在知道问题了.正是来自此帖子的CSS钩子我正在使用.我只是删除了该钩子,直接使用了rgb值,它开始正常运行.这是我更新的代码

I know the problem now. It was in that css hook from this post that i was using. i just removed that hook and directly have used rgb value and it started working perfectly. Here is my updated code

$(document).ready(function (e) {
        

     $('body *').each(function(index) {
    
         var rgbg = $(this).css('background-color');
         if(rgbg == "rgb(235, 44, 51)")
         {
                $(this).addClass('jcbg');
             
             }

    });

});

感谢@Guffa的摆弄.它帮助了我.

推荐答案

问题是,即使您声明为十六进制,jquery也会返回rgb(...),所以我只添加了函数将十六进制转换为rgb:

The problem is that jquery returns rgb(...) even if you declare as HEX so i just added a function to translate hex to rgb:

function hex2rgb(hex) {
  return ['0x' + hex[1] + hex[2] | 0, '0x' + hex[3] + hex[4] | 0, '0x' + hex[5] + hex[6] | 0];
}

不仅仅是修改您的代码:

and than just adapted your code:

$(document).ready(function (e) {

    // Color to change
    var targetHex = hex2rgb('#eb2c33');

    $('body *').each(function(index) {         
        var rgbg = $(this).css('background-color');

        if(rgbg == 'rgb('+targetHex[0]+', '+targetHex[1]+', '+targetHex[2]+')'){
            $(this).addClass('jcbg');
        }

    });
});

这是小提琴

这篇关于将类添加到具有特定CSS属性的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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