点击后向前和向后更改html按钮的背景颜色

时间:2015-11-11 18:17:54

标签: javascript html

我是JavaScipt和HTML的新手,只需要它作为一个副作用。我有一些按钮,我希望他们的背景颜色在点击后改变。我可以部分解决:

<input class="choice" onclick="this.style.background='blue';" type="submit" value='V' id='0' />

然而,当第二次点击按钮时,它应该改回来。优选地是如上所述的单行语句。非常感谢任何帮助。

3 个答案:

答案 0 :(得分:0)

我把你的代码分解成单独的JS,它更干净,更容易维护。

如果您禁用该按钮,则会停止接收点击事件。我认为这不是你想要的。

在这里,我已经做到了这一点,当点击按钮时,它会切换红色和蓝色之间的背景颜色。

http://jsbin.com/huqoyixuhe/edit?html,css,js,output

// select the button
var input = document.querySelector('input.choice');
// add a click event listener
input.addEventListener('click', function () {
  // if the button is red, make it blue
  if (this.style.background === 'red') {
    this.style.background = 'blue';
  }
  // otherwise, it is already blue, so make it red! 
  else {
    this.style.background = 'red';
  }


});

修改

这里,作为一个单行: http://jsbin.com/bolowuceqa/edit?html,output

<input class="choice" onclick="this.style.background==='red' ? this.style.background = 'blue' : this.style.background = 'red'" style="background:red;" type="submit" value='V' id='0' />

答案 1 :(得分:0)

您可以通过纯javascript在类名称之间使用切换。

HTML:

<button id="toggole" class="red" onclick="toggolecolor()">
Click Please
</button>

CSS:.red{

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

Javascript:

function toggolecolor(){
 var element = document.getElementById("toggole");
  element.classList.toggle("red");
    element.classList.toggle("blue");

}

答案 2 :(得分:-2)

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
<body bgcolor="(color)"/>