替代颜色onClick

时间:2018-04-05 23:36:15

标签: function colors alternate

我正在开发一个javascript函数,每次按下按钮都会导致div元素的背景颜色在lavenderblush和cyan之间交替。

按下按钮一次,它会改变颜色,但第二次按下时不会改变颜色。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

据推测,背景颜色可以是3个值之一,"青色"," lavenderblush",其他任何

现在,如果逻辑是

Current          Changes to
--------------   -------------
cyan             lavenderblush
lavenderblush    cyan
*anything else*  lavenderblush

然后代码应该是

var style = document.getElementById('new').style;
if (style.backgroundColor === "lavenderblush") {
    style.backgroundColor = "cyan";
} else {
    style.backgroundColor = "lavenderblush";
}

或者,如果逻辑是

Current          Changes to
--------------   -------------
cyan             lavenderblush
lavenderblush    cyan
*anything else*  cyan

然后代码是

var style = document.getElementById('new').style;
if (style.backgroundColor === "cyan") {
    style.backgroundColor = "lavenderblush";
} else {
    style.backgroundColor = "cyan";
}

但是,如果逻辑是

Current          Changes to
--------------   -------------
cyan             lavenderblush
lavenderblush    cyan
*anything else*  *do not change*

然后代码是

var style = document.getElementById('new').style;
if (style.backgroundColor === "cyan") {
    style.backgroundColor = "lavenderblush";
} else if (style.backgroundColor === "lavenderblush") {
    style.backgroundColor = "cyan";
}

这是第一个"逻辑"作为一个可运行的片段



function Replace() {
    var style = document.getElementById('new').style;
    if (style.backgroundColor === "lavenderblush") {
        style.backgroundColor = "cyan";
    } else {
        style.backgroundColor = "lavenderblush";
    }
}
document.getElementById('Replace').addEventListener('click', Replace);

<button id="Replace">Click</button>
<div id="new">NEW</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

让您的生活更轻松,并使用classList API以编程方式处理样式更改。

专门结帐.toggle()。它是一种原生解决方案。不需要Deps,只需更简单的逻辑来处理所有问题。欢呼声。

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList