js 父组件阻止子组件onmouseenter事件执行
时间: 2025-02-08 11:43:55 浏览: 24
### 解决方案
为了防止父组件响应子组件的 `onmouseenter` 事件,可以通过修改事件传播行为实现这一目标。具体来说,在子组件中处理 `onmouseenter` 事件时调用 `event.stopPropagation()` 方法能够有效阻止该事件向上传播至父级元素[^1]。
```html
<div id="parent">
<div id="child"></div>
</div>
<script>
document.getElementById('child').addEventListener('mouseenter', function(event) {
event.stopPropagation();
console.log('Child mouseenter');
});
// Parent will not log 'Parent mouseenter' when hovering over child element.
document.getElementById('parent').addEventListener('mouseenter', function() {
console.log('Parent mouseenter');
});
</script>
```
通过上述代码片段展示的方式,当鼠标悬停于子元素之上时,仅会触发子元素内的日志记录语句;而不会引发任何针对其父容器的操作或反应。这表明 `stopPropagation` 成功拦截了原本可能传递给上级节点 (`<div id="parent">`) 的 `mouseenter` 事件通知。
阅读全文
相关推荐







