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

如何用CSS实现遮罩层显示时背景内容可滚动

解决遮罩层显示时背景内容仍可滚动的问题

问题场景

当前设置了绝对定位的遮罩层覆盖在可滚动内容区域上,但遮罩层显示时无法滚动下方内容,现有代码如下:

CSS代码

.main{
  position: relative;
}
.masked-content {
  height: 150px;
  overflow: auto;
 
}
.mask {
   background-color: rgba(255, 255, 255, 0.7);
  position: absolute;
    top: 0px;
    left: 0;
    width: 100%;
    cursor: default;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    }

HTML代码

<div class="main">
  <div class="masked-content">This is some text covered by the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the maskSome contents above the mask</div>

  <div>
    <div class="mask">Some contents above the mask</div>
  </div>
</div>

解决思路

遮罩层默认会捕获所有鼠标事件,导致下方可滚动区域无法响应滚动操作。只需修改遮罩层CSS,让它不拦截鼠标事件即可:

  • 给.mask添加pointer-events: none属性,遮罩层会忽略所有鼠标交互,事件会穿透到下方内容区域。
  • 如果遮罩层内部有需要交互的元素(如按钮、可点击文本),给这些内部元素设置pointer-events: auto,恢复它们的交互能力。

修改后的CSS代码

.main{
  position: relative;
}
.masked-content {
  height: 150px;
  overflow: auto;
 
}
.mask {
   background-color: rgba(255, 255, 255, 0.7);
  position: absolute;
    top: 0px;
    left: 0;
    width: 100%;
    cursor: default;
    height: 150px;
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
    pointer-events: none; /* 添加此行实现事件穿透 */
    }
/* 若遮罩层内有需要交互的元素,添加以下样式恢复交互 */
.mask .interactive-element {
    pointer-events: auto;
}

修改后,遮罩层显示时下方的.masked-content区域可正常滚动,同时遮罩层内的交互元素也能正常响应操作。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 15:10:59