触发警报:新手问题。
我正在尝试更改按钮的颜色,从灰色开始。在第一次单击时,我希望它变为绿色,在第二次单击时,我希望它变为红色,然后在每次单击时在绿色和红色之间切换。
问题是一旦它变成绿色,我就不能让它工作了。如果我在代码中手动将start值设置为绿色,则else If会起作用,并将按钮变为红色,但如果我从灰色按钮开始并单击它以使其变为绿色,则不会。
如何让它在第一次单击时变为绿色,在第二次单击时变为红色,然后在每次单击时在红色和绿色之间切换?
Html:
<input type="button" id="button1" class="button" onclick="colorChange()" value="Click Here" />javascript:
function colorChange() {
var button = document.getElementById('button1').style.backgroundColor;
var color = '';
if (color !== 'green') {
color = 'green';
document.getElementById('button1').style.backgroundColor = color;
}
else if (color == 'green') {
color = 'red';
document.getElementById('button1').style.backgroundColor = color;
}
}和css类(如果有关系):
.button {
background-color: #909090;
color: #d3d3d3;
font-size: 16px;
padding: 10px 20px;
border-radius: 10px;
border: 0px;
}注意:可能有更好的方法和其他技术来做到这一点,但我的目的是了解它是如何工作的(以及为什么它目前不工作)。
发布于 2017-06-30 20:08:10
var button = document.getElementById('button1');
var color = button.style.backgroundColor;
button.addEventListener('click', function () {
// this function executes whenever the user clicks the button
color = button.style.backgroundColor = color === 'green' ? 'red' : 'green';
});.button {
background-color: #909090;
color: #d3d3d3;
font-size: 16px;
padding: 10px 20px;
border-radius: 10px;
border: 0px;
}<input type="button" id="button1" class="button" value="Click Here" />
这是一个较短的版本:
document.getElementById('button1').addEventListener('click', function () {
this.style.backgroundColor = this.style.backgroundColor === 'green' ? 'red' : 'green';
});.button {
background-color: #909090;
color: #d3d3d3;
font-size: 16px;
padding: 10px 20px;
border-radius: 10px;
border: 0px;
}<input type="button" id="button1" class="button" value="Click Here" />
发布于 2017-06-30 20:04:30
你需要改变你的状况
function colorChange() {
var button = document.getElementById('button1').style.backgroundColor;
var color = '';
if (button !== 'green') {
color = 'green';
document.getElementById('button1').style.backgroundColor = color;
}
else if (button === 'green') {
color = 'red';
document.getElementById('button1').style.backgroundColor = color;
}
} .button {
background-color: #909090;
color: #d3d3d3;
font-size: 16px;
padding: 10px 20px;
border-radius: 10px;
border: 0px;
}<input type="button" id="button1" class="button" onclick="colorChange()" value="Click Here" />
发布于 2017-06-30 20:05:33
以简单的方式,您可以使用数组并循环遍历这些值。
i = -1;
var bg = ["green", "red"];
function colorChange(which) {
which.style.backgroundColor = bg[i++ % bg.length];
}.button {
background-color: #999;
color: #d3d3d3;
font-size: 16px;
padding: 10px 20px;
border-radius: 10px;
border: 0px;
}<input type="button" id="button" class="button" onclick="return colorChange(this);" value="Click Here" />
https://stackoverflow.com/questions/44846038
复制相似问题