首页 > 解决方案 > 按钮样式错误

问题描述

我想使用按钮从我的用户那里接收信息,所以我为此创建了两个部分。当用户单击一个按钮时,我需要它来更改其样式,以便用户即使单击另一部分中的另一个按钮也会看到他们单击的内容有所不同。问题是,当单击另一个按钮时,另一个部分会失去其样式(因此用户不会知道他之前单击了什么)。我粘贴了有问题的部分的html代码(下)

<div>
    <p><strong>Network</strong></p>

     <button class="btn25" onclick = "gfg_Run()">                  
         MTN
     </button>
     <button class="btn25">         
         Glo
     </button>
     <button class="btn25">         
         9 Mobile
     </button>
     <button class="btn25">          
          Airtel
     </button>
</div>

<div>
     <p><strong>Data</strong></p>

     <button class="btn25">        
         1Gb
     </button>
     <button class="btn25">        
         2Gb
     </button>
     <button class="btn25">         
         3Gb
     </button>
     <button class="btn25">       
          5Gb
     </button>
     <button class="btn25">         
          10Gb
     </button>
</div>

标签: javascripthtmlcss

解决方案


我需要它来改变它的风格,这样用户就会看到不同

创建一个class被调用active,然后设置按钮以在用户选择它们时使用该类。

问题是,当单击另一个按钮时,另一个部分会失去其样式

问题是您需要将每个组分开。我在区分两组class的父级上添加了一个:“数据”或“速度”。div每个组的按钮背景将变为蓝色,因为它仅限于查询中的该类,如“.data”在此处所做的那样:

document.querySelectorAll('.data .btn25');

这是一个显示基本技术的示例片段。

const dataChoices = document.querySelectorAll('.data .btn25');
dataChoices.forEach(function(choice) {
  choice.addEventListener('click', function() {
    removeClass(dataChoices);
    this.classList.add('active');
  });
});

const speedChoices = document.querySelectorAll('.speed .btn25');
speedChoices.forEach(function(choice) {
  choice.addEventListener('click', function() {
    removeClass(speedChoices);
    this.classList.add('active');
  });
});

function removeClass(dataGroup) {
  dataGroup.forEach(function(choice) {
    choice.classList.remove('active');
  });
}
.active {
  background-color: lightblue;
}

div {
  float: left;
  margin-right: 10px;
}
<div class="data">
  <p><strong>Data</strong></p>
  <button id="1" class="btn25">1Gb</button>
  <button id="2" class="btn25">2Gb</button>
  <button id="3" class="btn25">3Gb</button>
  <button id="4" class="btn25">5Gb</button>
  <button id="5" class="btn25">10Gb</button>
</div>
<div class="speed">
  <p><strong>Speed</strong></p>
  <button id="1" class="btn25">1Mbps</button>
  <button id="2" class="btn25">2Mbps</button>
  <button id="3" class="btn25">3Mbps</button>
  <button id="4" class="btn25">5Mbps</button>
  <button id="5" class="btn25">10Mbps</button>
</div>


推荐阅读