【问题标题】:How can I change the background of each element with a specific class on mouseover?如何在鼠标悬停时更改具有特定类的每个元素的背景?
【发布时间】:2021-12-06 21:47:20
【问题描述】:

我正在尝试在鼠标悬停时使用“标题”类更改元素的背景。

const heading = document.querySelector('.heading');
const headingAll = document.querySelectorAll('.heading');
headingAll.forEach(item => {
  item.addEventListener("mouseover",()=>{
    heading.style.backgroundColor='teal';
  });
})
.heading{
  background-color: yellow;
  width: 50%;
  margin:0 auto;
  padding: 10px;
  border: 1px solid red;
  cursor: pointer;
}

.heading2,heading3{
  margin-top: 10px;
}
<h1 id='heading' class='heading heading2'>First Heading</h1>
<h2 id='heading' class='heading heading2'>Sub Heading</h2>
<h3 id='heading' class='heading heading3'>Third Heading</h3>

问题在于,只有第一个具有“标题”类的元素的背景才会发生变化。我不知道如何使它适用于其他元素。我怎样才能做到这一点?

【问题讨论】:

  • querySelectorAll 是你要找的
  • id 应该是唯一的,不能重复。
  • 您的问题是heading 变量引用了与传递给querySelector() 的选择器匹配的第一个元素。使用item.style.backgroundColor='teal' 而不是header.style.backgroundColor='teal'

标签: javascript addeventlistener mouseover


【解决方案1】:

在您的代码 sn-p 中,您没有遵循您在 forEach 回调函数中设置的迭代器变量。将其更改为item 而不是heading,它应该可以工作。

const headingAll = document.querySelectorAll('.heading');
headingAll.forEach(item => {
  item.addEventListener("mouseover",()=>{
    item.style.backgroundColor='teal';
  });
})
.heading{
  background-color: yellow;
  width: 50%;
  margin:0 auto;
  padding: 10px;
  border: 1px solid red;
  cursor: pointer;
}

.heading2,heading3{
  margin-top: 10px;
}
<h1 id='heading' class='heading heading2'>First Heading</h1>
<h2 id='heading' class='heading heading2'>Sub Heading</h2>
<h3 id='heading' class='heading heading3'>Third Heading</h3>

请注意,我删除了您的 heading 变量,因为它不需要在我的 sn-p 中使用。

【讨论】:

    【解决方案2】:

    您正在使用document.querySelector() 来获取具有类名标题的元素,如果有多个元素,它将只获取第一个。在这里,您需要使用 item 而不是 heading 来更改要添加 mouseover 事件的元素样式。

    【讨论】:

      猜你喜欢
      • 2012-10-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-16
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多