code demo

设计思想

本项目将拖拽系统拆分为两个核心模块:

  • Dragable → 提供拖拽能力
  • Invoker → 提供拖拽规则

因此任何拖拽行为都可以通过组合 Invoker 实现。

创建 Dragable

const el = document.getElementById("box") const drag = new Dragable(el)

拖拽生命周期

mousedown → beginDrag mousemove → move mouseup → endDrag

事件钩子

drag.addBeginDragFn(fn) drag.addMoveFn(fn) drag.addEndDragFn(fn)

每个 hook 都可以修改拖拽状态,例如限制移动距离。

可拖拽元素

new ShareDragable( document.querySelectorAll(".share") )
const invoker = new DragInvokerOfZIndex() invoker.add(new Dragable(el))
new DragInvokerOfLimitInArea(container) .add(new Dragable(el))
new DragInvokerOfLimitDirection({ x:true, y:false })
new DragInvokerOfExclusion( drag1, drag2 )
new DragInvokerOfSnap( drag, hook, 80)

当拖拽元素中心点和目标元素中心点距离小于 80px 时(即在白色区域内), 拖拽元素会自动吸附到目标元素中心。