首页 > 解决方案 > 我无法使用此代码在单击时更改类背景颜色。为什么?

问题描述

$(document).ready(function(){
    function checker() {
       if ($(".check-box-label").css("background-color") === "none"){
           $(".check-box-label").css("background-color", "#1F7566")
       }else{
           $(".check-box-label").css("background-color", "none")
       }
    };
});

$(".check-box-label").on("click", checker);

使用此代码, .check-box-label 背景颜色应该在点击时根据实际背景颜色值交替颜色,为什么它不起作用?谢谢

标签: jqueryhtmlcss

解决方案


几个问题,

1.).css("backgroundColor")返回 rgb,而不是 hex,所以我添加了一个常用的方法,用于转换为 hex

2.) 将背景颜色设置为无,将不起作用。您需要改用“透明”或“初始”

function rgb2hex(rgb) {
     if (  rgb.search("rgb") == -1 ) {
          return rgb;
     } else {
          rgb = rgb.match(/^rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+))?\)$/);
          function hex(x) {
               return ("0" + parseInt(x).toString(16)).slice(-2);
          }
          return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]); 
     }
}

function checker() {
   var targetColor = "#1f7566";
   var color = $(".check-box-label").css("backgroundColor");
   console.log(rgb2hex(color), rgb2hex(color) != targetColor)
   if (rgb2hex(color) != targetColor){
       $(".check-box-label").css("background-color", targetColor)
   }else{
       $(".check-box-label").css("background-color", "initial")
   }
};

$(".check-box-label").on("click", checker);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label class="check-box-label">
things
</label>


推荐阅读