鍍金池/ 問答/HTML/ js中 style.backgroundColor能識別red或blue,卻無法

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"
    }
     
    
}
回答
編輯回答
耍太極

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

2018年3月8日 11:04
編輯回答
陌上花

轉(zhuǎn)換成rgb

fd4d4f => rgb(253, 77, 79)

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

2018年8月23日 10:57
編輯回答
故林

需要轉(zhuǎn)成 rgb。很簡單,寫一個轉(zhuǎn)換函數(shù):

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")){
    ...
}

當然,也可以不用我的函數(shù),可以寫成:

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

剛剛突然開了個腦洞。其實也可以這樣寫:
var parseClr = function() {

// 創(chuàng)建一個節(jié)點
var dom = document.createElement("div"); 
// 以彼之道還之彼身
return function(clr) {
    dom.style.backgroundColor = clr;
    return dom.style.backgroundColor;  
}

}();

理論上說上面的代碼是可以兼容所有瀏覽器的顏色轉(zhuǎn)換。

2017年9月22日 02:44