Javascript - 如果语句工作,但其他没有

时间:2018-03-11 14:56:39

标签: javascript html colors onclick

我有一个在单击特定元素时运行的脚本。脚本会更改div的背景颜色。当用户点击div时,背景颜色必须更改为#4aa3c3,但是当用户再次点击div时,它必须更改回#fafafa。 if语句有效,但由于某种原因,一旦颜色变为#4aa3c3,它就不会恢复正常。似乎我的其他声明不起作用。我做错了吗?

    function Active() {

    if (document.getElementById("test").style.backgroundColor !== "#4aa3c3"){
        document.getElementById("test").style.backgroundColor = "#4aa3c3";
        } else {
        document.getElementById("test").style.backgroundColor = "#fafafa";
        }
}

2 个答案:

答案 0 :(得分:7)

当你尝试一些基本的调试时,比如

console.log(document.getElementById('test').style.backgroundColor);

你看到了问题吗?机会是,你得到的东西是:

"rgb(74, 163, 195)"

这就是为什么if无法正常工作的原因。但这不是你最大的问题。

真正的问题是您使用Presentation(CSS)来定义行为(JS)。最重要的是,您使用行为来定义演示文稿。

相反,你应该这样做:

document.getElementById('test').classList.toggle('toggled');

使用CSS定义如下样式:

#test {background-color: #fafafa}
#test.toggled {background-color: #4aa3c3}

答案 1 :(得分:0)

同意上面的答案 - 但是要添加另一个维度 - 如果您确实需要将返回的RBG值更改为十六进制,您可以尝试这样的方法,这样可以使代码按原始问题中的说明工作。 / p>

<script>


function hex(x) {
    return ("0"+x.toString(16)).slice(-2);
}

function rgb2hex(rgb) {
    rgb = rgb.match(/^rgb\((\d+),\s*(\d+),\s*(\d+)\)$/);
    return "#" + hex(rgb[1]) + hex(rgb[2]) + hex(rgb[3]);
}

function CheckIfColorIsCorrect()
{

        var hex = rgb2hex(document.getElementById("test").style.backgroundColor);

        if (hex != "#4aa3c3"){
        document.getElementById("topbar").style.backgroundColor = "#4aa3c3";
        } else {
        document.getElementById("test").style.backgroundColor = "#fafafa";
        }
}
</script>