我会尽力解释我想做什么。如果类超过2,如何在多个类之间切换?当我单击彩色按钮时,容器颜色类将被添加/交换。当我单击白色按钮时,它将删除容器颜色类。
下面是一个JSFiddle示例,以便更好地理解:https://jsfiddle.net/bwd86h4e/1/
我希望有人能帮忙。
谢谢。
HTML格式:

<div class="buttons">
  <div class="btn btn-reset"></div>
  <div class="btn btn-red"></div>
  <div class="btn btn-green"></div>
  <div class="btn btn-yellow"></div>
</div>

<div class="container">
  When I click on the colored buttons above, then container color class will exchanged. When I click on the white button, then it removes container color class. How to do it?
</div>

CSS:
/* Buttons */
.btn {
  display: inline-block;
  width: 30px;
  height: 30px;
  margin: 3px;
  cursor: pointer;
  border: 2px solid #333;
}
.btn.btn-red { background-color: red; }
.btn.btn-green { background-color: green; }
.btn.btn-yellow { background-color: yellow; }

/* Container */
.container {
  max-width: 480px;
  margin-top: 20px;
  padding: 40px;
  border: 2px solid #333;
}

/* Container color classes */
.container.cont-red { background-color: red; }
.container.cont-green { background-color: green; }
.container.cont-yellow { background-color: yellow; }

最佳答案

纯javascript如下:

var buttons = document.querySelectorAll(".btn");
var container = document.getElementById("container_1");
var container_color_classes = ["cont-red","cont-green","cont-yellow"];

buttons.forEach(function(button){
		button.addEventListener("click", function(){
  	container_color_classes.forEach(function(color){
    	container.classList.remove(color);
    })
    var className = this.getAttribute("data-class");
    if(className !== null)
    	container.classList.add(className);
  });
});

/* Buttons */
.btn {
  display: inline-block;
  width: 30px;
  height: 30px;
  margin: 3px;
  cursor: pointer;
  border: 2px solid #333;
}
.btn.btn-red { background-color: red; }
.btn.btn-green { background-color: green; }
.btn.btn-yellow { background-color: yellow; }

/* Container */
.container {
  max-width: 480px;
  margin-top: 20px;
  padding: 40px;
  border: 2px solid #333;
}

/* Container color classes */
.container.cont-red { background-color: red; }
.container.cont-green { background-color: green; }
.container.cont-yellow { background-color: yellow; }

<div class="buttons">
  <div class="btn btn-reset"></div>
  <div class="btn btn-red" data-class="cont-red"></div>
  <div class="btn btn-green" data-class="cont-green"></div>
  <div class="btn btn-yellow" data-class="cont-yellow"></div>
</div>

<div class="container" id="container_1">
  When I click on the colored buttons, then container color class will added/exchanged. When I click on the white button, then it removes container color class. <strong>How to do it?</strong>
</div>

08-19 07:40