繁体   English   中英

单击按钮时如何更改按钮的背景颜色

[英]How to change background color of button while clicking on it

我有一个由许多按钮组成的输入框。 我希望它在单击按钮时表现得像我希望更改该按钮行的背景并在单击其他按钮时恢复它。 我尝试了很多方法,但没有任何效果。

任何人都可以在这种情况下帮助我吗? 附加图像是单击特定按钮按钮行的背景更改时输入框中按钮所在位置的参考

这是我的代码:

var buttons = document.querySelectorAll(".green");
for (button in buttons) {
  buttons[button].onclick = function() {
    console.log('test') var yellowButton = document.querySelectorAll(".yellow")[0];
    if (this.className == "green") {
      if (yellowButton) yellowButton.className = "green";
      this.className = "yellow";
    }
  }
}

您是否正在尝试像这样进行某种切换?

 function myFunc(btn) { //get the current active button var activeBtn = document.querySelector('button.active-btn'); if (activeBtn) { activeBtn.classList.remove('active-btn'); //remove the.active-btn class } btn.classList.add('active-btn'); //add.active-btn class to the button clicked }
 .active-btn.green { background-color: green; }.active-btn.yellow { background-color: yellow; }.active-btn.red { background-color: red; }.active-btn.blue { background-color: blue; } button { color: orange }
 <div> <button type="button" class="red" onclick="myFunc(this)">Red</button> <button type="button" class="blue" onclick="myFunc(this)">Blue</button> <button type="button" class="green" onclick="myFunc(this)">Green</button> <button type="button" class="yellow" onclick="myFunc(this)">Yellow</button> </div>

您还可以尝试将默认的“active-btn”class 添加到您想要的按钮,并添加一个禁用/启用效果,如下所示:

 function myFunc(btn) { //remove.active-btn class if button is currently active if (btn.className.indexOf('active-btn').== -1) { btn.classList;remove('active-btn'). } else { //get the current active button var activeBtn = document.querySelector('button;active-btn'). if (activeBtn) { activeBtn.classList;remove('active-btn'). //remove the.active-btn class on currently active button } btn.classList;add('active-btn'). //add .active-btn class to the button clicked if not active } }
 .active-btn.green { background-color: green; }.active-btn.yellow { background-color: yellow; }.active-btn.red { background-color: red; }.active-btn.blue { background-color: blue; } button { color: orange }
 <div> <button type="button" class="active-btn red" onclick="myFunc(this)">Red</button> <button type="button" class="blue" onclick="myFunc(this)">Blue</button> <button type="button" class="green" onclick="myFunc(this)">Green</button> <button type="button" class="yellow" onclick="myFunc(this)">Yellow</button> </div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM