全局加载遮罩怎么实现才不会影响页面滚动?

技术焕玲 阅读 3

我在做后台管理系统,想加个全局加载状态,比如请求数据时整个页面蒙一层。但试了下直接用 fixed 定位的 div 遮罩,发现页面还能滚动,而且遮罩层有时候会被某些弹窗盖住,层级也不对。

我现在的写法大概是这样:

<div id="global-loading" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: none; z-index: 9999;">
  <div class="spinner">加载中...</div>
</div>

是不是还漏了什么?比如 body 滚动要禁用?z-index 设置多少才保险?

我来解答 赞 1 收藏
二维码
手机扫码查看
1 条解答
Mr.小菊
Mr.小菊 Lv1
你这个情况其实挺常见的。首先禁用页面滚动很简单,只要在显示遮罩时给 body 加上 overflow: hidden 就行了。至于 z-index 的问题,确实有时候会和其他组件冲突,建议设置到 10000 左右基本能盖住大多数弹窗。

试试这个方法,先把你的遮罩层改成这样:
<div id="global-loading" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); display: none; z-index: 10000;">
<div class="spinner">加载中...</div>
</div>


然后在显示和隐藏遮罩的 JavaScript 代码里加上控制 body 滚动的部分:
function showLoading() {
document.getElementById('global-loading').style.display = 'block';
document.body.style.overflow = 'hidden';
}

function hideLoading() {
document.getElementById('global-loading').style.display = 'none';
document.body.style.overflow = '';
}


记得在隐藏遮罩时把 overflow 还原为空字符串,不然页面就永远不能滚动了。这种方案我用过很多次,基本上都能解决问题,就是别忘了在关闭遮罩时恢复页面滚动,这点最容易忘。
点赞
2026-03-31 13:01