如何使用jquery查找具有特定颜色的元素

How to find element has specific color using jquery

本文关键字:颜色 元素 何使用 jquery 查找      更新时间:2023-09-26

这是我的HTML代码

<ul id="components">
    <li>Computer</li>
    <li>Mouse</li>
    <li>Keyboard</li>
    <li>Printer</li>
    <li>CPU</li>
</ul>
#components li:first-child{
    color:red;
}
#components li: nth-child(2){
    color:blue;
}
#components li: nth-child(3){
    color:red;
}
#components li: nth-child(4){
    color:red;
}
#components li: nth-child(5){
    color:green;
}

我需要的是一个jQuery函数,它可以red颜色找到所有li元素,并且可以将背景转换为黄色

我的意思是像

$("#components").find(li elements in red color).css("backgound","yellow"); 
// find li elements in red color and change the background to yellow
您可以使用

.filter();

 $('ul li').filter(function() {
   return $(this).css('color') == 'rgb(255, 0, 0)';
 }).each(function() {
   $(this).css('background-color', 'yellow');
 })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script>
<ul id="components">
  <li style="color:red">Computer</li>
  <li style="color:blue">Mouse</li>
  <li style="color:red">Keyboard</li>
  <li style="color:red">Printer</li>
  <li style="color:green">CPU</li>
</ul>

您可以使用属性选择器 [attr=value]演示

$('ul li[style="color:red"]').css('background', 'yellow');

你也可以用纯CSS来做到这一点。

ul#components li[style="color:red"] {
  background: yellow;
}
<ul id="components">
  <li style="color:red">Computer</li>
  <li style="color:blue">Mouse</li>
  <li style="color:red">Keyboard</li>
  <li style="color:red">Printer</li>
  <li style="color:green">CPU</li>
</ul>

更新:这不是最好的方法,但您可以检查每个 li 的颜色,并返回rbg并添加背景演示

$('ul li').each(function() {
  var color = $(this).css('color');
  if (color == 'rgb(255, 0, 0)') $(this).css('background', 'yellow');
})

您可以使用.filter()来过滤元素选择。在函数中使用style.color属性filter()来获取元素的颜色。

$("#components > li").filter(function(){
    return this.style.color == "red";
}).css("background-color", "yellow");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="components">
    <li style="color:red">Computer</li>
    <li style="color:blue">Mouse</li>
    <li style="color:red">Keyboard</li>
    <li style="color:red">Printer</li>
    <li style="color:green">CPU</li>
</ul>

试试,

$('li[style="color:red"]').css('background-color','yellow')

$('li[style="color:red"]').attr('style','color:red;background-color:yellow;')

或者使用 each() 循环

var allLi=$('li')
$.each(allLi,function(k,v){
if($(v).attr('style')=='color:red')
{
$(v).css('background-color','yellow')
}
})

工作 JSFiddle