Layui移动端需手动实现左滑唤出侧边栏,核心是监听touch事件判断左滑、控制侧边栏DOM显隐及遮罩层,并通过响应式控制仅在移动端生效。

Layui 默认的导航栏不支持移动端左滑唤出侧边栏,需要手动集成手势监听 + 抽屉动画 + 响应式控制。核心是用 touchstart/touchmove/touchend 判断左滑动作,并触发 Layui 自带的 layui.layer.open 抽屉或自定义侧边栏 DOM 显示。
1. 准备一个可隐藏/显示的侧边栏 DOM 结构
在页面中添加一个固定定位、初始隐藏的侧边栏容器(建议放在 <body> 内最外层):
<div id="mobileSidebar" class="layui-side layui-bg-black" style="position: fixed; top: 0; left: -240px; width: 240px; height: 100%; z-index: 999; transition: left 0.3s ease;">
<div class="layui-side-scroll">
<ul class="layui-nav layui-nav-tree">
<li class="layui-nav-item"><a href="#home">首页</a></li>
<li class="layui-nav-item"><a href="#list">列表页</a></li>
<li class="layui-nav-item"><a href="#about">关于</a></li>
</ul>
</div>
</div>注意:设置 left: -240px 实现初始隐藏,transition 保证滑入滑出有动画。
2. 添加触摸滑动检测逻辑(判断左滑)
监听 document 的 touch 事件,记录起始 X 坐标,松开时计算位移差,大于阈值(如 50px)且方向为左滑则展开侧边栏:
let startX = 0;
let isDragging = false;
<p>document.addEventListener('touchstart', function(e) {
if (e.touches.length === 1) {
startX = e.touches[0].clientX;
isDragging = true;
}
}, { passive: true });</p><p>document.addEventListener('touchend', function(e) {
if (!isDragging) return;
const endX = e.changedTouches[0].clientX;
const diff = startX - endX;</p><p>// 左滑且位移足够(>50px),且页面未滚动(避免误触)
if (diff > 50 && Math.abs(window.scrollY) < 10) {
document.getElementById('mobileSidebar').style.left = '0';
}
isDragging = false;
}, { passive: true });</p>3. 点击遮罩或返回按钮关闭侧边栏
给侧边栏加个半透明遮罩层(或监听点击空白区域),并提供关闭按钮:
- 在侧边栏外加一个全屏遮罩:
<div id="sidebarMask" style="position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.5); z-index: 998; display: none;"></div> - 展开时同时显示遮罩:
document.getElementById('sidebarMask').style.display = 'block'; - 绑定遮罩点击关闭:
document.getElementById('sidebarMask').onclick = () => { document.getElementById('mobileSidebar').style.left = '-240px'; document.getElementById('sidebarMask').style.display = 'none'; }; - 在侧边栏顶部加一个「×」按钮,点击同样执行关闭逻辑
4. 响应式控制:仅在移动端生效
避免 PC 端误触发,用媒体查询或设备宽度判断:
- 方法一(推荐):只在屏幕宽度 ≤ 768px 时启用滑动手势
- 方法二:用
if (/Android|webOS|iPhone|iPod|iPad|BlackBerry/i.test(navigator.userAgent))粗略判断移动端 - 记得在 PC 浏览器缩放窗口时,也要动态监听
window.matchMedia更新开关状态
不复杂但容易忽略的是:滑动过程中要防止页面默认滚动行为干扰(可在 touchmove 中加 e.preventDefault(),但需谨慎,避免影响内容滚动;更稳妥做法是只在侧边栏未展开且横向滑动明显时才阻止)。


















