繁体   English   中英

在按钮组中选择时按钮颜色更改

[英]Button color change when selected in button group

我在一个 HTML 页面上有 2 个按钮组。 每组 3 到 4 个按钮(使用引导程序的按钮)。 我想在没有 onclick 的情况下单击时使用 Javascript 更改颜色按钮。

  1. 用户将单击组 1 中的任何按钮(单击将颜色更改为绿色时)并单击组 2 中的按钮,而不取消选择组 1 中的按钮。

 .show { display: block; }.btn-group { margin-top: 20px; overflow: hidden; }.btn { font-weight: bold; color: white; border: none; outline: none; padding: 12px 16px; /*blue*/ background-color: #2c75ff; cursor: pointer; }.btn:hover { font-weight: bold; color: white; /*green*/ background-color: #85c995; }
 <div class="row"> <div class="column" style="width:30%"> <div class="btn-group" > <button type="button" class="btn btn-primary" style="outline-color:red; ">Sunday</button> <button type="button" class="btn btn-primary" >Tuesday</button> <button type="button" class="btn btn-primary" >Friday</button> </div> </div> <div class="column" style="width:70%"> <div class="btn-group" > <button type="button" class="btn btn-primary" >9 am</button> <button type="button" class="btn btn-primary">2 pm</button> <button type="button" class="btn btn-primary">5 pm</button> <button type="button" class="btn btn-primary" >8 pm</button> </div> </div> </div>

首先,给第一组按钮一个 ID,如下所示:

<div class="row">
  <div class="column" style="width:30%">
    <div class="btn-group" id="btn-group-a">
      <button type="button" class="btn btn-primary" style="outline-color:red; ">Sunday</button>
      <button type="button" class="btn btn-primary" >Tuesday</button>
      <button type="button" class="btn btn-primary" >Friday</button>
    </div>
  </div>
  <div class="column" style="width:70%">
    <div class="btn-group" >
      <button type="button" class="btn btn-primary" >9 am</button>
      <button type="button" class="btn btn-primary">2 pm</button>
      <button type="button" class="btn btn-primary">5 pm</button>
      <button type="button" class="btn btn-primary" >8 pm</button>
    </div>
  </div>
</div>

现在,我们可以使用 javaScript 中的forEach循环为该组中的每个按钮分配事件侦听器。

如果你已经有一个.js文件,下面的代码可以 go 在那里。 否则,请在 HTML 的末尾添加一个<script></script>标记并将其添加到那里。

const groupA = document.querySelector("#btn-group-a");
// get our div with buttons

const groupABtns = groupA.querySelectorAll("button");
// select all of our buttons within this div

// Loop through our array of buttons, and add a click event for each
groupABtns.forEach(btn => {
    addEventListener("click", () => {
        btn.style.backgroundColor = 'green'
    });
})

这将遍历第一组中的按钮数组,并为每个按钮添加一个事件侦听器。 现在,每个按钮都有一个style属性集,将其背景颜色更改为绿色。

我希望这就是你所追求的。

** 另请注意,这实际上并没有“选择”任何按钮,只是将它们的颜色更改为绿色。 该功能会稍微复杂一些。 **

暂无
暂无

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

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