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

点击覆盖层后方p元素为何跳过其onclick?点击传播问题解析

点击固定定位覆盖层后方的p标签时,为何会跳过p的onclick事件?

示例代码

CSS

.overlay {
  position: fixed;
  width: 200px;
  height: 150px;
  top: 0;
  left: 0;
  z-index: 1;
  background-color: rgba(255, 0, 0, 0.7);
  cursor: pointer;
}

img.overlay__first-child {
  position: fixed;
  top: -25px;
  right: -25px;
  width: 50px;
  height: 50px;
  z-index: 3;
  cursor: pointer;
  background-color: green;
}

.overlay img {
  position: relative;
  z-index: 2;
}

.overlay__second-child {
  width: 100px;
  height: 100px;
  background-color: blue;
}

HTML

<div class="no-styling" onclick="console.log('no-styling')">
  <div class="overlay" onclick="console.log('overlay')">
    <img src="#" class="overlay__first-child" onclick="console.log('overlay__first-child')" />
    <img src="#" class="overlay__second-child" onclick="console.log('overlay__second-child')" />
  </div>

  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
  <p onclick="console.log('p')">Content to create a scrollbar</p>
</div>

问题现象

点击覆盖层(.overlay)后方的p文本时,控制台只会打印no-styling,不会打印p;将p换成button标签也会出现同样的事件传播跳跃现象。只有点击未被遮挡的p元素时,才会正常打印p和no-styling,该现象在Firefox和Chrome中均可复现。

点击位置说明:除未被遮挡的最下方区域外,其余被覆盖层遮挡的位置点击后,只会触发对应子元素(若存在)、overlay和no-styling的事件,完全跳过p的事件;未被遮挡的位置则正常触发p和no-styling的事件。

原因解析

核心原因是固定定位(position: fixed)的元素会脱离正常文档流,形成独立的层叠上下文,并且.overlay的z-index:1让它的层叠顺序高于正常文档流中的p标签。

当你点击视觉上被覆盖层挡住的p区域时,实际点击的目标元素是最上层的.overlay,而不是下方的p标签。事件触发后会从.overlay开始向上冒泡,最终到达父元素.no-styling,但p标签不在这个事件的传播路径上,所以它的onclick不会被触发。

只有当点击位置没有被任何脱离文档流的元素覆盖时,点击事件才会命中p标签,进而触发它的事件并向上冒泡到.no-styling。

内容的提问来源于stack exchange,提问作者Daniel Kaplan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 06:02:11