GSAP Draggable问题:点击拖拽元素后上层内容消失
问题解决:拖拽背景后上层内容消失的修复
核心原因
GSAP Draggable插件默认开启autoZIndex: true,拖拽时会自动提升.draggable-content的z-index值,直接覆盖你的上层内容;同时.main-container未设置相对定位,导致绝对定位的.non-draggable-content定位参考上下文不符合预期,加剧了显示异常。
修复方案
方案1:禁用Draggable的自动z-index提升
在Draggable配置中添加autoZIndex: false,阻止插件修改拖拽元素的层级:
Draggable.create(".draggable-content", { type: "x", bounds: document.querySelector(".main-container"), inertia: true, dragClickables: false, autoZIndex: false, // 新增配置 onClick: function () { console.log("clicked"); }, onDragEnd: function () { console.log("drag ended"); }, });
方案2:修正定位上下文
给.main-container设置相对定位,让绝对定位的上层内容以它为参考基准,确保层级优先级稳定:
.main-container { position: relative; /* 新增定位规则 */ } .non-draggable-content { position: absolute; top: 0; left: 50%; transform: translateX(-50%); z-index: 2; }
推荐组合方案
将两个方案结合,彻底解决层级冲突和定位问题:
修改后的styles.css
.main-container { position: relative; } .non-draggable-content { position: absolute; top: 0; left: 50%; transform: translateX(-50%); z-index: 2; }
修改后的main.js
Draggable.create(".draggable-content", { type: "x", bounds: document.querySelector(".main-container"), inertia: true, dragClickables: false, autoZIndex: false, onClick: function () { console.log("clicked"); }, onDragEnd: function () { console.log("drag ended"); }, });
修改完成后,.non-draggable-content会始终固定在.main-container上方,不会被拖拽操作影响显示。
内容的提问来源于stack exchange,提问作者Anushka Chauhan
相关产品推荐
相关产品推荐

