首页 > 解决方案 > 如何为活动按钮之前的所有按钮设置相同的颜色,并为活动按钮旁边的所有按钮设置相同的颜色?

问题描述

我在设置按钮样式时遇到问题。我需要的是,活动按钮和活动之前的所有按钮都具有相同的颜色,而活动按钮旁边的所有按钮都具有其他颜色。这可以在javascript中实现吗?

代码:

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
  font-size: 18px;
}
.active, .btn:hover {
  background-color: #666;
  color: white;
}
.mystyle{
    background-color:gold;
}

</style>
</head>
<body>

<h1>Active Button</h1>
<p>Highlight the active/current (pressed) button.</p>
  
<div id="myDIV">
  <button class="btn">1</button>
  <button class="btn">2</button>
  <button class="btn">3</button>
  <button class="btn">4</button>
  <button class="btn">5</button>
</div>

<script>
// Add active class to the current button (highlight it)
var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("btn");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
  var current = document.getElementsByClassName("active");
  if (current.length > 0) { 
    current[0].className = current[0].className.replace(" active", "");
    
  }
  this.className += " active";
  this.previousSibling.className += " mystyle";
  });
}
</script>

</body>
</html>

标签: javascripthtmlcss

解决方案


我希望它对你有所帮助。

function removeClasses() {
  for(var i=1;i<=5;i++) {
    $('#'+i+'').removeClass('active');
    $('#'+i+'').removeClass('mystyle');
    $('#'+i+'').removeClass('next');
  }
}

function activeButton(id) {
  id = parseInt(id);
  
  removeClasses();
  
  $('#'+id+'').addClass('active');
  for(var j=1;j<=(id-1);j++) $('#'+j+'').addClass('mystyle');
  for(var j=(id+1);j<=5;j++) $('#'+j+'').addClass('next');
}
.btn {
  border: none;
  outline: none;
  padding: 10px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
  font-size: 18px;
}
.active, .btn:hover {
  background-color: #666;
  color: white;
}
.mystyle{
    background-color:gold;
}
.next {
  background-color:green;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>

<h1>Active Button</h1>
<p>Highlight the active/current (pressed) button.</p>
  
<div id="myDIV">
  <button id="1" onclick="activeButton(this.id)" class="btn">1</button>
  <button id="2" onclick="activeButton(this.id)" class="btn">2</button>
  <button id="3" onclick="activeButton(this.id)" class="btn">3</button>
  <button id="4" onclick="activeButton(this.id)" class="btn">4</button>
  <button id="5" onclick="activeButton(this.id)" class="btn">5</button>
</div>

</body>
</html>


推荐阅读