gpt4 book ai didi

javascript - 针对 :hover DOM with querySelectorAll 的问题

转载 作者:太空宇宙 更新时间:2023-11-03 22:12:01 24 4
gpt4 key购买 nike

当鼠标悬停在 li 标签上时,我无法将其背景颜色更改为红色。

摘自 javascript.info

Can use pseudo-classes as well: Pseudo-classes in the CSS selector like :hover and :active are also supported. For instance, document.querySelectorAll(':hover') will return the collection with elements that the pointer is over now (in nesting order: from the outermost to the most nested one).

let hover = document.querySelectorAll('li:hover');

for (let elem of hover) {
elem.style.background = 'red';
};
<div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
</div>

最佳答案

您最好将 mouseentermouseleave 事件监听器添加到 li 标记本身,而不是尝试根据:hover 选择器。当文档加载时,没有一个被悬停,所以集合是空的。

let hover = document.querySelectorAll('li');

for (let elem of hover) {
elem.addEventListener('mouseenter', () => {
elem.style.backgroundColor = 'red'
})
elem.addEventListener('mouseleave', () => {
elem.style.backgroundColor = ''
})
};
<div>
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>a</li>
<li>b</li>
<li>c</li>
<li>d</li>
</ul>
</div>

关于javascript - 针对 :hover DOM with querySelectorAll 的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58922567/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com