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

Ant Design Drawer打开时页面仍可滚动,该如何禁止页面滚动?

Ant Design Drawer打开时禁止页面滚动解决方案

方案1:使用官方内置属性(推荐,适配v4.16.0+、v5全版本)

Ant Design的Drawer组件原生提供lockScroll配置项,默认值为true,开启后会在抽屉弹出时自动锁定背景页面滚动。如果你的场景中该配置失效,可以显式声明该属性:

<Drawer
  title="抽屉标题"
  open={isDrawerOpen}
  onClose={handleClose}
  lockScroll={true} // 显式开启滚动锁定
>
  抽屉内部内容
</Drawer>

如果你的抽屉通过getContainer属性挂载到了自定义DOM节点而非默认的body下,lockScroll会自动失效,这种场景要么调整getContainer为默认值,要么参考方案2手动控制。


方案2:手动控制滚动(兼容低版本/自定义挂载场景)

如果使用v4.16.0之前的旧版本Ant Design,或者抽屉挂载到了自定义容器,可以监听抽屉的显隐状态,手动修改body样式实现滚动锁定:

import { useState, useEffect } from 'react';
import { Drawer, Button } from 'antd';

export default function Demo() {
  const [isOpen, setIsOpen] = useState(false);

  useEffect(() => {
    // 抽屉打开时锁定页面
    if (isOpen) {
      document.body.style.overflow = 'hidden';
      // 移动端iOS兼容可以额外加以下样式
      // document.body.style.position = 'fixed';
      // document.body.style.width = '100%';
    } else {
      // 关闭时恢复滚动
      document.body.style.overflow = 'auto';
      // 对应iOS兼容的恢复逻辑
      // document.body.style.position = 'static';
      // document.body.style.width = 'auto';
    }
    // 组件卸载时恢复样式,避免页面滚动异常
    return () => {
      document.body.style.overflow = 'auto';
      // document.body.style.position = 'static';
      // document.body.style.width = 'auto';
    };
  }, [isOpen]);

  return (
    <>
      <Button onClick={() => setIsOpen(true)}>打开抽屉</Button>
      <Drawer
        title="自定义锁定滚动抽屉"
        open={isOpen}
        onClose={() => setIsOpen(false)}
      >
        抽屉内容
      </Drawer>
    </>
  );
}

不生效常见排查点

  • 检查全局样式是否给html、body节点设置了height: 100%、overflow-x: hidden等属性,可能会覆盖滚动锁定的样式
  • 确认没有其他组件或全局逻辑在抽屉打开后修改了body的overflow属性
  • 移动端iOS场景下如果仍有滚动穿透,按照方案2中的注释添加position: fixed相关样式即可解决

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 12:54:03