码迷,mamicode.com
首页 > 编程语言 > 详细

基于html5拖拽api实现列表的拖拽排序

时间:2018-09-27 14:12:00      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:ret   handle   selector   rop   insert   []   targe   https   clear   

基于html5拖拽api实现列表的拖拽排序

html代码:

<ul ondrop="drop_handler(event);" ondragover="dragover_handler(event);">
    <li draggable="true" ondragstart="dragstart_handler(event);">1</li>
    <li draggable="true" ondragstart="dragstart_handler(event);">2</li>
    <li draggable="true" ondragstart="dragstart_handler(event);">3</li>
    <li draggable="true" ondragstart="dragstart_handler(event);">4</li>
    <li draggable="true" ondragstart="dragstart_handler(event);">5</li>
</ul>

js代码:

var uls = document.querySelector(‘ul‘);
var offsetTop = uls.offsetTop;
var clientX = ‘‘;
var clientY = ‘‘;
var n = 0;
function dragstart_handler(ev) {
      console.log("dragStart");
      ev.target.setAttribute(‘id‘, ‘test1‘)
      ev.dataTransfer.setData("text/plain", ev.target.id);
}

function dragover_handler(ev) {
      ev.preventDefault();
      clientX = ev.clientX;
      clientY = ev.clientY;
      n = Math.round((clientY - offsetTop)/52)        //52代指拖拽元素的高度    
}

function drop_handler(ev) {
      console.log("Drop");
      ev.preventDefault();
      var data = ev.dataTransfer.getData("text");
      console.log(n)
      var nodes = document.getElementById(data);
      uls.insertBefore(nodes, children(uls)[n]);
      nodes.removeAttribute(‘id‘);
      ev.dataTransfer.clearData();
}
function children(node){
      var tmp = node.childNodes;
      var arr = [];
      tmp.forEach(function(item){
           if(item.nodeType == 1){
               arr.push(item);
           }
      });
      return arr;
}

效果展示:

技术分享图片

基于html5拖拽api实现列表的拖拽排序

标签:ret   handle   selector   rop   insert   []   targe   https   clear   

原文地址:https://www.cnblogs.com/guojikun/p/9712507.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!