Dragula是一款支持移动触摸屏设备的纯js元素拖放插件。这个元素拖放插件使用简单,浏览器兼容性好,能够实现通过鼠标或在移动设备中通过手指来拖动DOM元素的位置。它的特点有:
- 设置非常简单
- 没有外部依赖
- 可以自动对数据进行排序
- 被移动项带有半透明的视觉效果
- 支持移动触摸设备
- 兼容性好,支持IE7+的所有现代浏览器
安装
可以通过bower或npm来安装该元素拖放插件。
npm install dragula --save
bower install dragula.js --save
使用方法
该元素拖动插件提供了一个最简单的API来让你可以在页面中拖放元素。
dragula(containers, options?)
默认情况下,dragula允许用户在containers中拖动一个元素,并将元素放置到containers列表的其它容器中。如果元素被放置在containers列表元素之外,插件将取消revertOnSpill和removeOnSpill选项。
注意:拖拽事件只会发生在用户鼠标左键点击的时候,并且没有meta键被按下。如果点击的是按钮或超链接元素,拖拽事件也会被忽略。
下面的例子允许用户将元素从left容器拖放到right容器,或从right容器拖放到left容器中。
dragula([left, right]);
配置参数
你也可以为它提供一些参数选项:
dragula(containers, {
moves: function (el, container) {
return true; // elements are always draggable by default
},
accepts: function (el, target, source, sibling) {
return true; // elements can be dropped in any of the `containers` by default
},
direction: 'vertical', // Y axis is considered when determining where an element would be dropped
copy: false, // elements are moved by default, not copied
revertOnSpill: false, // spilling will put the element back where it was dragged from, if this is true
removeOnSpill: false // spilling will `.remove` the element, if this is true
});
- options.moves:你可以定义一个
moves方法,该方法在发生点击的时候通过(el, container)参数进行调用。如果该方法返回的是false,拖拽事件将不会开始,事件也不会被阻止。 - options.accepts:该方法确保一个来自
source的元素el能够在sibling元素之前放入到target容器之中。sibling元素可以为null,这会使元素被放置到容器的最后一个位置。注意:如果options.copy设置为true,el元素会被设置为一个副本,替代原始的拖放元素。 - options.copy:如果
copy设置为true,元素将被复制而不是拖动。注意下面的区别:Event Move Copy drag 元素从 source中隐藏Nothing happens drop 元素将移动到 target中元素会被克隆到 target中remove 元素会从DOM中移除 Nothing happens cancel 元素会停留在 source中Nothing happens - options.revertOnSpill:默认情况下,元素被拖放到容器之外会被放置到由
feedback shadow设定的投放点上。设置revertOnSpill为true将确保元素在拖放到容器之外时会被重新放置会拖放的开始位置。 - options.removeOnSpill:设置
removeOnSpill为true会使任何拖放到容器之外的元素被从DOM中移除。注意:如果copy设置为true,remove事件将不会触发。 - options.direction:当元素被拖放到一个容器中,它将被放置到最接近鼠标位置的点上。如果
direction设置为vertical,将会使用Y轴坐标作为参考带你,如果设置为horizontal会使用X轴坐标作为参考点。
事件
- drake.end():使用最后位置的预览阴影标记最为拖放的目的地拖放元素。相应的
cancel或drop事件将被触发。 - drake.cancel(revert):如果被
drake管理的元素是当前被拖放的元素,这个方法会取消拖放事件。你也可以在该方法的调用级别中传入revert参数,效果与revertOnSpill设置为true相同。注意:一个"cancellation"将在下面的场景中会返回一个"cancel"事件:revertOnSpill设置为true- 放置的目标(半透明的预览图)在source容器中,并且元素被放置到相同的容器中。
- drake.remove():如果被
drake管理的元素是当前被拖放的元素,该方法会将元素从DOM中移除。 - drake.on (Events):
drake是一个事件发送器。下面的事件可以使用drake.on(type, listener)来跟踪。事件名称 参数 描述 drag el, container el从container中被拖拽drop el, container, source el被放置到container中,它来自sourcecancel el, container el被拖动但仍在原处,并最终回到containerremove el, container el被拖动但仍在原处,并最终被从DOM中移除。shadow el, container el是拖放目的地的半透明预览,它会移动到container中。 - drake.destroy():移除所有的拖放事件。如果
.destroy在一个元素被拖动时触发,拖动将不会有效果。