如何创建从右侧弹出、仅占自身80%宽度的modal bottom sheet组件
右侧弹出式modal bottom sheet组件实现方案
我们可以通过CSS定位、过渡动画配合简单的交互逻辑实现该组件,80%展示宽度的需求可通过CSS属性直接控制。
核心实现逻辑
- 组件默认隐藏在视口右侧外部,触发后通过平移动画滑入视口,展示宽度固定为视口总宽度的80%
- 弹出时同步显示半透明遮罩层,阻断底层页面交互
- 支持点击遮罩层、关闭按钮两种收起方式
完整代码示例
HTML结构
<!-- 触发按钮(可替换为自定义图标) --> <button id="triggerBtn">☰</button> <!-- 遮罩层 --> <div id="mask" class="mask"></div> <!-- 右侧弹出bottom sheet组件 --> <div id="rightSheet" class="right-sheet"> <div class="sheet-content"> <p>面板内部自定义内容</p> <button id="closeBtn">关闭</button> </div> </div>
CSS样式
* { margin: 0; padding: 0; box-sizing: border-box; } /* 触发按钮样式 可根据需求自定义 */ #triggerBtn { position: fixed; top: 20px; right: 20px; padding: 8px 12px; cursor: pointer; } /* 遮罩层样式 */ .mask { position: fixed; inset: 0; background: rgba(0,0,0,0.5); z-index: 999; opacity: 0; visibility: hidden; transition: all 0.3s ease; } .mask.show { opacity: 1; visibility: visible; } /* 右侧弹出面板核心样式 */ .right-sheet { position: fixed; top: 0; right: 0; height: 100vh; width: 80%; /* 控制展示宽度为总宽度的80% */ max-width: 480px; /* 可选:设置最大宽度避免大屏下面板过宽 */ background: #fff; box-shadow: -2px 0 12px rgba(0,0,0,0.1); z-index: 1000; transform: translateX(100%); /* 默认隐藏在视口外 */ transition: transform 0.3s ease; } .right-sheet.show { transform: translateX(0); /* 弹出后滑入视口 */ } .sheet-content { padding: 24px; }
交互逻辑(JavaScript)
const triggerBtn = document.getElementById('triggerBtn') const closeBtn = document.getElementById('closeBtn') const rightSheet = document.getElementById('rightSheet') const mask = document.getElementById('mask') // 弹出面板 triggerBtn.addEventListener('click', () => { rightSheet.classList.add('show') mask.classList.add('show') document.body.style.overflow = 'hidden' // 禁止背景滚动 }) // 关闭面板 function closeSheet() { rightSheet.classList.remove('show') mask.classList.remove('show') document.body.style.overflow = 'auto' } closeBtn.addEventListener('click', closeSheet) mask.addEventListener('click', closeSheet)
如果使用Vue、React等前端框架开发,仅需将类名切换逻辑替换为对应框架的状态控制逻辑即可,核心CSS样式可以直接复用。
内容的提问来源于stack exchange,提问作者Amiden
相关产品推荐
相关产品推荐

