繁体   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