要让 layui layer 弹窗记住拖拽位置,需在 moveEnd 回调中用 layero.css('left/top') 获取并保存坐标到 localStorage,打开前读取并设为 offset;fixed 必须为 false,且在 end 回调中清除缓存。

要让 layui layer 弹窗记住用户上次拖拽后的位置,需在关闭时保存 left/top 值到 localStorage 或 sessionStorage,并在下一次打开时读取并传给 offset;不能依赖 layer 自身配置,必须手动接管坐标生命周期。
保存拖拽结束位置到本地存储
在 layer.open 的 moveEnd 回调中获取当前弹窗容器的 left 和 top 值,转为数字后存入 localStorage。注意:moveEnd 是唯一可靠时机——此时 DOM 已更新,且避免在拖动中频繁写入。
layer.open({
type: 1,
content: '<div>表单内容</div>',
drag: true,
moveEnd: function(layero, index) {
const left = parseFloat(layero.css('left')) || 0;
const top = parseFloat(layero.css('top')) || 0;
localStorage.setItem('layer_pos_' + index, JSON.stringify({ left, top }));
}
});
⚠️ 必须用 layero.css('left') 而非 layero.style.left —— 后者在 fixed 定位下可能为空字符串,前者能正确返回带单位的值(如 "120px"),parseFloat 才能安全提取数值。
读取并应用上次位置打开弹窗
每次调用 layer.open 前,先查 localStorage 中对应 key 的记录。若存在,构造 offset 数组;若不存在或解析失败,则 fallback 到默认居中或预设位置。
const posKey = 'layer_pos_' + Date.now(); // 实际项目建议用稳定标识,如模块名
let lastPos = null;
try {
lastPos = JSON.parse(localStorage.getItem(posKey) || 'null');
} catch(e) {}
layer.open({
type: 1,
content: '<div>表单内容</div>',
offset: lastPos ? [lastPos.top + 'px', lastPos.left + 'px'] : 'auto',
fixed: false // ⚠️ 【fixed 必须设为 false】,否则 offset 坐标会被 layer 内部 scrollY 补偿逻辑覆盖,导致位置漂移
});
绑定关闭事件清除过期位置数据
第一步:在 layer.open 的 end 回调中,主动删除该层对应的位置缓存。不删会导致旧位置长期残留,尤其当弹窗被脚本反复销毁重建时。
第二步:若弹窗支持最小化/最大化(maxmin: true),还需监听 min 和 restore 回调,在最小化时不删、恢复时也不删——仅在真正销毁时清理。
第三步:为防 localStorage 溢出,可加时间戳字段,在读取时判断是否超过 7 天,超期则自动丢弃并清除。
layer.open({
type: 1,
content: '<div>表单内容</div>',
end: function(index) {
localStorage.removeItem('layer_pos_' + index);
}
});


















