如何为Node List添加事件监听?实现grid中.block元素鼠标悬停变色
解决.gridcontainer内div.block鼠标悬停变色问题
你当前代码存在两个核心问题:
document.querySelector(".block")仅能选中页面中第一个带.block类的元素,导致只有首个方块能触发悬停变色效果。- 通过
addGrid动态生成的新.block元素,未绑定鼠标悬停事件,无法响应变色逻辑。
以下是两种可行解决方案:
方案一:事件委托(推荐)
利用事件冒泡机制,将鼠标悬停事件绑定到父容器.gridcontainer上。无论初始存在还是动态生成的.block元素,触发事件后都会冒泡到父容器,通过判断目标元素的类名来执行变色逻辑,这种方式更高效,尤其适合大量元素的场景。
修改后的完整JS代码:
// 事件委托:给父容器绑定事件 const gridContainer = document.querySelector(".gridcontainer"); gridContainer.addEventListener("mouseover", (event) => { if (event.target.classList.contains("block")) { event.target.style.backgroundColor = "green"; } }); let newGrid = document.querySelector('button'); newGrid.addEventListener("click", event => { if (event.target.nodeName == "BUTTON") { deleteChild(); let userInput = howMany(); let input = userInput * userInput; let pixel = 500 / userInput; for (let i = 0; i < input; i++) { addGrid(pixel); } } }); function howMany() { let userInput = prompt("how many?"); return userInput; } function addGrid(pixel) { let container = document.querySelector(".gridcontainer"); let grid = document.createElement('div'); grid.classList.add('block'); // 规范的类名添加方式,避免覆盖原有类 grid.textContent = 'hi'; grid.style.height = pixel + 'px'; grid.style.width = pixel + 'px'; container.appendChild(grid); } function deleteChild() { let e = document.querySelector(".gridcontainer"); let child = e.lastElementChild; while (child) { e.removeChild(child); child = e.lastElementChild; } }
方案二:给每个动态元素单独绑定事件
在addGrid函数中,每次创建新的.block元素后,直接为其绑定鼠标悬停事件。注意要删除原有仅针对首个元素的事件绑定代码。
修改后的addGrid函数:
function addGrid(pixel) { let container = document.querySelector(".gridcontainer"); let grid = document.createElement('div'); grid.classList.add('block'); grid.textContent = 'hi'; grid.style.height = pixel + 'px'; grid.style.width = pixel + 'px'; // 给当前新元素绑定悬停事件 grid.addEventListener("mouseover", () => { grid.style.backgroundColor = "green"; }); container.appendChild(grid); }
配套CSS代码
.gridcontainer { display: flex; width: 500px; height: 500px; flex-direction: row; gap: 0px; /* 修正原代码的0x错误 */ flex-wrap: wrap; } .block { display: flex; flex-direction: column; text-align: center; color: blue; }
配套HTML代码
<button>Change Canvas</button> <div class="gridcontainer"> <div class="block" style="height: 31.25px; width: 31.25px;">hi</div> <div class="block" style="height: 31.25px; width: 31.25px;">hi</div> <div class="block" style="height: 31.25px; width: 31.25px;">hi</div> <div class="block" style="height: 31.25px; width: 31.25px;">hi</div> <div class="block" style="height: 31.25px; width: 31.25px;">hi</div> <div class="block" style="height: 31.25px; width: 31.25px;">hi</div> <div class="block" style="height: 31.25px; width: 31.25px;">hi</div> <div class="block" style="height: 31.25px; width: 31.25px;">hi</div> </div>
内容的提问来源于stack exchange,提问作者hbz19
相关产品推荐
相关产品推荐

