简体   繁体   English

如何使用 JavaScript 选择 div 元素并更改背景颜色?

[英]How to select a div element with JavaScript and change background color?

So, on my website I have a pop-up modal that contains a form.所以,在我的网站上,我有一个包含表单的弹出式模式。 The form has 5 divs that contain a picture and a description.该表单有 5 个 div,其中包含图片和说明。 I found the following JS code on w3schools that enables me to select a div and give it the styling I want.我在 w3schools 上找到了以下 JS 代码,它使我能够选择一个 div 并为其设置我想要的样式。 However, when I first open the modal, one div is selected.但是,当我第一次打开模态时,选择了一个 div。 But I don't want any to be selected.但我不希望任何人被选中。 I am not sure how to modify this code to make it so no divs are seleced initially.我不确定如何修改此代码以使其最初不选择任何 div。

      // When user clicks an div, add background
      var divs = document.getElementsByClassName("mood-state");
      for (var i = 0; i < divs.length; i++) {
        divs[i].addEventListener("click", function () {
          var current = document.getElementsByClassName("active");
          current[0].className = current[0].className.replace(" active", "");
          this.className += " active";
        });
      }

Here is some of the div in the modal这是模态中的一些 div

            <div class="mood-state">
              <img src="neutral.svg" alt="" />
              <p>Neutral</p>
            </div>
            <div class="mood-state">
              <img src="smile.svg" alt="" />
              <p>Pleasant</p>
            </div>
            <div class="mood-state active">
              <img src="grin.svg" alt="" />
              <p>Very Pleasant</p>
            </div

Remove the active class in the HTML.删除 HTML 中的active类。 Having that there makes it initially start as active.有了它,它最初开始时是活跃的。

<div class="mood-state active"> <-- You have the active class here
  <img src="grin.svg" alt="" />
  <p>Very Pleasant</p>
</div>

Change that to将其更改为

<div class="mood-state"> <-- No 'active' class here
  <img src="grin.svg" alt="" />
  <p>Very Pleasant</p>
</div>

You also need to change your JavaScript to fix a bug您还需要更改 JavaScript 以修复错误

// When user clicks an div, add background
var divs = document.getElementsByClassName("mood-state");
for (var i = 0; i < divs.length; i++) {
  divs[i].addEventListener("click", function() {
    [...document.getElementsByClassName("active")].forEach(ele => ele.classList.remove("active"));
    this.classList.add("active");
  });
}

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

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