You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何阻止父div的点击事件传递给子div

实现父容器覆盖时子容器不响应点击操作

需求描述

我有一个覆盖整个页面的父<div>,内部包含一个尺寸更小的子<div>。需要实现的效果是:当父<div>覆盖子<div>时,子<div>不会响应点击操作。

解决方案代码

HTML 代码

<body>
  <div onclick="parentFunction(event)" class="parent">
      <div onclick="childFunction()" class="child">
          子容器
      </div>
  </div>
</body>

阻止冒泡:
<input type="checkbox" id="check">

CSS 代码

.child {
  padding: 50px;
  width: 100px;
  height: 100px;
  background-color: hotpink;
  text-align: center;
  cursor: pointer;
}

.parent {
    width: 100vw; /* 设置为100vw实现覆盖页面宽度 */
    height: 100vh; /* 设置为100vh实现覆盖页面高度 */
    filter: blur(2px);
    display: flex;
    justify-content: center; /* 修正原代码拼写错误 */
    align-items: center;
    background-color: lightgray;
}

JavaScript 代码

function parentFunction(event) {
  if (document.getElementById("check").checked) {
    event.stopPropagation();
  }
}

function childFunction() {
  alert("子容器被点击了");
}

代码说明

  • 父容器适配调整:将原代码中父容器的固定宽高改为100vw和100vh,确保它能覆盖整个页面;同时修正了justifc-content的拼写错误为justify-content,保证子容器能居中显示。
  • 事件拦截逻辑:勾选"阻止冒泡"复选框后,点击父容器区域会触发event.stopPropagation(),阻止事件向子容器传递。此时点击子容器区域,事件会被父容器拦截,不会触发子容器的点击事件;取消勾选时,子容器的点击事件会正常触发,弹出提示框。

内容的提问来源于stack exchange,提问作者four-eyes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 02:35:24