js中 style.backgroundColor能识别red或blue,却无法识别如#1fe26d的颜色代码吗?

如下,当c.style.backgroundColor=="red"时 我可以通过点击
已占用
在红色和蓝色之间切换div颜色
可是,一旦改为 if(c.style.backgroundColor=="#fd4d4f"){

            c.style.backgroundColor="#1fe26d";
            
            }else{
                    c.style.backgroundColor="#fd4d4f"
            }

就无法切换了

<div class="info-box1 bg-fff" style="height: 135px;border:0;background-color: #fd4d4f;">

            <p style="font-size: 25px;color: white;"><a title="信息" href="javascript:;"onclick="xiang('包厢信息','xiang.html','1','700','600')"><strong>101</strong></a></p>
            <p style="font-size: 20px;color: white;">(8人)</p>
            <hr style="color: white;">
            <a style="text-decoration:none;">
            <p style="font-size: 20px;color: white;padding-top: 15px;"  class="test">
                <Strong id="1" onclick="changeColor(this)">已占用</Strong>
            </p>
            </a>
        </div>
 
function changeColor(obj) {
    var a = obj.parentNode;
    var b = a.parentNode;    
    var c = b.parentNode; 
    
    if(c.style.backgroundColor=="red"){  //判断,倘若为红色,则变绿
            c.style.backgroundColor="blue";
            
    }else{
            c.style.backgroundColor="red"
    }
     
    
}
阅读 4k
3 个回答

转换成rgb

fd4d4f => rgb(253, 77, 79)

1fe26d=> rgb(31, 226, 109)

需要转成 rgb。很简单,写一个转换函数:

function hex2rgb(hex) {
    hex = hex.replace(/\#|\s/g, ""); 
    var r, g, b; 
    // 简写
    if(hex.length === 3) {
        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2]; 
    }
    // 补全
    else {
       hex = (hex + "000000").substring(0, 6);  
    }
    r = +("0x" + hex.substring(0, 2)), g = +("0x" + hex.substring(2, 4)), b = +("0x" + hex.substring(4, 6)); 
    return "rgb(" + r + ", " + g + ", " + b + ")"; 
}

你可以把原代码改成:

 if(c.style.backgroundColor == hex2rgb("#fd4d4f")){
    ...
}

当然,也可以不用我的函数,可以写成:

 if(c.style.backgroundColor == "rgb(" + 0xfd + ", " + 0x4d + ", " + 0x4f + ")"){
    ...
}

刚刚突然开了个脑洞。其实也可以这样写:
var parseClr = function() {

// 创建一个节点
var dom = document.createElement("div"); 
// 以彼之道还之彼身
return function(clr) {
    dom.style.backgroundColor = clr;
    return dom.style.backgroundColor;  
}

}();

理论上说上面的代码是可以兼容所有浏览器的颜色转换。

mdn上click事件的浏览器异常处理

Known workarounds for this bug:
For IE9 only:
Set background-color: rgba(0,0,0,0)
Set opacity: 0 and an explicit background-color other than transparent
For IE8 and IE9: Set filter: alpha(opacity=0); and an explicit background-color other than >transparent

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题