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

时间:2020-07-28 06:56:12

标签: javascript css angular typescript

我有一个包含许多按钮的输入框。我希望它的行为就像单击按钮时一样。我希望更改按钮行的背景,并在单击其他按钮时将其还原。 我尝试了很多方法,但是没有用。

在这种情况下,有人可以帮助我吗?Attached image is the reference where in input box buttons are there when clicking on particular button button row's background changes

这是我的代码:

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";
    }
  }
}

1 个答案:

答案 0 :(得分:1)

您是否要像这样进行某种切换?

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”类,并添加禁用/启用效果,如下所示:

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>