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

如何解决CSS中z-index导致子元素无法触发鼠标事件的问题

解决方案

问题出在给子div设置z-index: -1后,子元素会被父容器(或更高层级的默认元素)遮挡,导致鼠标事件无法触发。以下是两种可行的解决思路:

思路1:使用半透明背景色替代z-index

直接给子div的背景色添加透明度,让父容器的背景图透出来,同时保留子元素的交互性:

/* About us section styles */
.aboutus-contact-us-wrapper {
  background-image: url('https://images.unsplash.com/photo-1667998641206-3eaa8f7047cd?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=459&q=80');
  background-size:  300px;
  background-position: right center;
  background-repeat: no-repeat;
}

.about-us-section {
  position: relative;
  width: 100%;
  height: 100vh;
  /* 用rgba设置半透明背景色 */
  background-color: rgba(241, 241, 241, 0.9);
  font-family: 'Lato' !important;
  /* 移除z-index: -1 */
}

.contact-us {
  width: 100%;
  height: 100vh;
  /* 用rgba设置半透明背景色 */
  background-color: rgba(24, 31, 43, 0.9);
  position: relative;
  color: #ffffff;
  /* 移除z-index: -1 */
}

思路2:将父容器背景图放到伪元素中

给父容器添加一个绝对定位的伪元素,承载背景图并设置z-index: -1,子div无需调整层级,自然能保留交互性:

/* About us section styles */
.aboutus-contact-us-wrapper {
  position: relative; /* 必须设置相对定位,让伪元素基于它定位 */
}

/* 用伪元素承载背景图 */
.aboutus-contact-us-wrapper::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image: url('https://images.unsplash.com/photo-1667998641206-3eaa8f7047cd?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8&auto=format&fit=crop&w=459&q=80');
  background-size:  300px;
  background-position: right center;
  background-repeat: no-repeat;
  z-index: -1; /* 伪元素在底层,不影响子元素交互 */
}

.about-us-section {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #F1F1F1;
  font-family: 'Lato' !important;
  /* 移除z-index: -1 */
}

.contact-us {
  width: 100%;
  height: 100vh;
  background-color: #181f2b;
  position: relative;
  color: #ffffff;
  /* 移除z-index: -1 */
}

两种方案都能让子div内的元素正常触发鼠标事件,同时父容器的背景图可以透过子div显示(思路1是半透明效果,思路2是背景图在最底层完全显示)。

内容的提问来源于stack exchange,提问作者Sohaib Ashraf

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 05:35:29