如何用原生JS结合querySelectorAll实现鼠标移入时修改对应元素样式
问题描述
有6组如下嵌套结构的HTML代码:
<div class="example" id="example1"> <div class="note"> <div class="backgr_color"></div> <div class="note_text"> <h2>Text</h2> <h3>Text</h3> <div class="note_comment"> <p>Text</p> </div> <div class="note_bottom"> <p>text</p> </div> </div> </div> </div>
其中class="note"的div是方形容器,内部class="backgr_color"的div是容器内的小点。需求是:鼠标移入对应的note容器时,修改对应backgr_color元素的尺寸和颜色,不想重复6次使用getElementById,要求用querySelectorAll实现,不使用jQuery。
目前已能通过遍历notes_animation修改note自身样式,但不清楚如何找到对应的backgr_color元素,现有代码如下:
let notes_animation = document.querySelectorAll(".note"); let backgr_color = document.querySelectorAll(".backgr_color"); for (i = 0; i < notes_animation.length; i++) { notes_animation[i].addEventListener('mouseenter', function () { this.style.backgroundColor = "red"; }); }
解决方案
不需要单独获取所有backgr_color元素,直接在mouseenter事件里,通过当前触发事件的note容器(也就是this)去查找它内部的backgr_color元素即可,用querySelector方法就能精准定位到当前容器下的目标元素。
修改后的代码如下:
let notes_animation = document.querySelectorAll(".note"); for (let i = 0; i < notes_animation.length; i++) { notes_animation[i].addEventListener('mouseenter', function () { // 修改note自身样式 this.style.backgroundColor = "red"; // 找到当前note下的backgr_color元素 const targetDot = this.querySelector(".backgr_color"); // 修改该元素的尺寸和颜色 targetDot.style.width = "20px"; targetDot.style.height = "20px"; targetDot.style.backgroundColor = "#00ff00"; }); // 鼠标移出后恢复样式,提升交互体验 notes_animation[i].addEventListener('mouseleave', function () { this.style.backgroundColor = ""; const targetDot = this.querySelector(".backgr_color"); targetDot.style.width = ""; targetDot.style.height = ""; targetDot.style.backgroundColor = ""; }); }
代码说明
this.querySelector(".backgr_color"):this指向当前触发鼠标移入事件的note容器,调用querySelector只会在这个容器内部查找匹配的元素,不会影响其他note里的backgr_color,完美对应到当前需要修改的小点。- 新增
mouseleave事件是为了鼠标移出后恢复原有样式,避免样式一直保留。 - 循环里用
let i而非全局的i,避免闭包导致的变量污染问题。
内容的提问来源于stack exchange,提问作者Eve Larson
相关产品推荐
相关产品推荐

