单击后前后更改html按钮的背景色

Changing the background color of html buttons forward and backward after clicks

本文关键字:按钮 背景色 html 单击      更新时间:2023-09-26

我是JavaScipt和HTML的新手,只需要它作为一个附带问题。我有一些按钮,我想在点击后更改它们的背景颜色。我可以用部分解决

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

但是,当第二次单击该按钮时,它应该会变回原来的状态。最好是像上面那样的一行语句。如果有任何帮助,我将不胜感激。

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

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

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

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

// 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,输出

<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' />

您可以通过纯javascript在类名之间使用toggole。

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");
}
<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
<body bgcolor="(color)"/>