onmousemove、onmouseenter、onmouseover 使用不生效问题
当我们在项目中使用鼠标事件
js
document.querySelector("#father").addEventListener('mousemove',(event) => {
console.log(1)
})
css
.father {
width: 300px;
height: 100px
border: 1px solid red;
}
html
<div id="father">
<span >
这是一段测试代码1
</span>
<span >
这是一段测试代码1
</span>
</div>
问题
当我们对上面div 设置onmousemove、onmouseenter、onmouseover事件处理时候,只有当鼠标在文字上才有生效。
解决方法
onmousemove事件在鼠标移动到 div 元素上时触发。
mouseenter 事件中有在鼠标指针进入 div 元素时触发。
onmouseover 事件在鼠标指针进入 div 元素时触发,在子元素上也会触发(p 和 span)
需要把div内当 标签改成
建议
获取html元素是,不建议使用document.querySelector而是使用document. getElementById(id)、getElementsByTagName
getElementById中id 不需要#
getElementsByTagName也返回一个数组
本文探讨了在使用onmousemove、onmouseenter、onmouseover等鼠标事件时遇到的问题,即这些事件仅在鼠标位于特定文本上时才触发。文章提供了修改建议,如调整内部标签结构,并推荐使用document.getElementById(id)替代document.querySelector来选取元素。
280

被折叠的 条评论
为什么被折叠?



