簡體   English   中英

Javascript:比較由JavaScript設置的backgroundColor

[英]Javascript: Compare backgroundColor set by javascript

當用javascript設置顏色時,如何比較元素的背景色,我想要一個可切換backgroundColor的函數:

function toggleBgColor() {
    if(document.getElementById("id").style.backgroundColor === "blue"){
        document.getElementById("ide").style.backgroundColor = "red");
    }else{
        document.getElementById("ide").style.backgroundColor = "blue");
    }
}

問題是比較總是錯誤的,所以我的背景總是藍色,但是當函數被調用時,它希望顏色從藍色切換為紅色,反之亦然

backgroundColor屬性在使用各種顏色表示時可能會比較棘手。 考慮改用類:

的JavaScript

function toggleBgColor() {
    var el = document.getElementById("id");
    var hasBlue = el.classList.contains('blue');
    el.classList.toggle('blue', !hasBlue);
    el.classList.toggle('red', hasBlue);
}

的CSS

.blue {
  background-color: blue;
}
.red {
  background-color:red;
}

或更符合語義的:

的JavaScript

function toggleBgColor() {
    document.getElementById("id").classList.toggle('selected');
}

的CSS

#id {
    background-color:red;
}
#id.selected {
    background-color:blue;
}

為什么不簡單地添加一個被切換的類呢?

function toggleBgClass() {
    var element = document.getElementById('id');

    if (element.classList.contains('blue')) {
        element.classList.add('blue');
        element.classList.remove('red');
    }
    else {
        element.classList.add('red');
        element.classList.remove('blue');
    }
}

現在,在您的CSS中:

.blue {
    background-color: blue;
}

.red {
    background-color: red;
}

您編寫了不正確的代碼。 正確的代碼是

    function toggleBgColor()
    {
       if(document.getElementById("ptag").style.backgroundColor === "blue")
       {
         document.getElementById("ptag").style.backgroundColor = "red";
       }
       else
       {   
         document.getElementById("ptag").style.backgroundColor = "blue";
       }
    };

HTML文件

<html>
    <head>
        <script type="text/javascript" src="js/backgroundtry.js"></script>
    </head>
    <body>
        <p id="ptag" style="background-color:blue;">
            Hi How are you
        </p>
        <a class="mybutton" onclick="toggleBgColor();">
            Change Color
        </a>
    </body>
</html>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM