首页 > 解决方案 > 切换多个 id 的类 (javascript)

问题描述

我有 2 个元素,每个元素都有不同的背景颜色,点击后,我想让它们变成不同的颜色。

如果元素还没有 background-color,下面是可以工作的代码:

html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <style media="screen">
    .buttons {
      width: 150px;
      height: 50px;
      border: solid 2px #999;
      text-align: center;
      color: black;
      cursor: pointer;
    }

      background-color: red;
    }
  </style>
</head>

<body>

  <div id="buttonGallery">
    <div id="button_1" class="buttons">
      <p>button_1</p>
    </div>
    <div id="button_2" class="buttons">
      <p>button_2</p>
    </div>
  </div>

  <script type="text/javascript">
    $("#button_1").click(function() {
      $('#button_1').toggleClass('selected');
    });
    $("#button_2").click(function() {
      $('#button_2').toggleClass('selected');
    });
  </script>
</body>
</html>

但是,如果我给每个 id 一个背景颜色,它们在单击时不会改变颜色:

  <style media="screen">
    .buttons {
      width: 150px;
      height: 50px;
      border: solid 2px #999;
      text-align: center;
      color: black;
      cursor: pointer;
    }

    #button_1 {
      background-color: blue;
    }

    #button_2 {
      background-color: green;
    }

    .selected {
      background-color: red;
    }

还有一种方法可以编写一个函数,在单击时将每个元素变为红色?(而不是为每个按钮写一个函数。我最终会有 8 个按钮。)谢谢!任何帮助将非常感激!

标签: javascripthtmlcss

解决方案


首先,.selected每次都会应用该类,但由于选择器优先级,它将被覆盖.button。所以有很多方法可以解决它。

您可以使用!important关键字(完全不推荐)

.selected {
  background-color: red !important;
}

注意:您应该尽可能避免使用!important键盘,但在您的特定情况下,这是最好的方法,但我强烈建议您更改样式方法并改用pseudo-class主类的选择器。像这样:

.buttons:first-of-type {
  background-color: blue;
}

.buttons:nth-of-type(2) {
  background-color: green;
}

/* and so on */

selected并为您的班级使用特定的方法,如下所示:

.buttons.selected {
  background-color: red;
}

或者

您可以使用直接但重复的方法。所以让你的.selected类选择器是这样的:

#button_1.selected, #button_2.selected /* and so on */ {
  background-color: red;
}

此外,为了简化您的 js 代码,您可以执行以下操作:

$('.buttons').click(function () {
  $(this).toggleClass("selected"); // $(this) keyword will refer to the clicked button, each time attribute with class buttons got clicked.
});


推荐阅读