jquery拖拽自动排序插件使用方法详解

本文为大家分享了jquery拖拽自动排序插件,供大家参考,具体内容如下

该插件并不是原生js写的,是基于jquery的,想看原生的话,请绕道而行。

html:

<!DOCTYPE html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <script type="text/javascript" src="jquery.js"></script>
 <script type="text/javascript" src="drag.js"></script>
 <style type="text/css">
  div{
   height: 200px;
   overflow-y: auto;
  }
  ul{
   margin: 0;
   padding: 0;
   list-style: none;
   box-shadow: rgba(0, 0, 0, 0.2) 5px 5px 10px;
   display: inline-block;
  }
  .drag-item{
   width: 100px;
   padding: 0 10px;
   line-height: 38px;
   cursor: move;
  }
  .draging{
   background-color: #ccc !important;
  }
  .no-draging{
   background-color: #fff !important;
  }
 </style>
</head>
<body>
 <ul class="drag-box">

 </ul>
</body>
<script type="text/javascript">
 new Drag({
  container: '.drag-box',
  data: ['应用1','应用2','应用3','应用4','应用5','应用6','应用7','应用8','应用9']
 });
</script>
</html>

js:

(function(win){

 function Drag(opts){
  this.init(opts);
 };

 Drag.prototype = {
  constructor: Drag,

  options: {
   container: '',
   data: [], //可以是数据,也可以是html标签
   className: 'item'
  },

  //初始化 
  init: function(opts){
   $.extend(this.options, opts);
   this.$el = $(this.get('container'));
   this._render();
   this._bindEvent();
  },

  get: function(key){
   return this.options[key];
  },

  set: function(key, value){
   this.options[key]=value;
  },

  //渲染列表
  _render: function(){
   var me = this, lis = '',
    data = me.get('data') || [];
   for(var i=0,len=data.length;i<len;i++) lis+='<li class="drag-item" id="drag-item-'+i+'">'+ data[i]+'</li>';
   me.$el.append(lis)
     .find('li').attr('draggable',true)
        .addClass(this.get('className'));
  },

  //绑定事件
  _bindEvent: function(){
   var me = this,
    $lis = $('li', me.$el),
    events = ['dragstart', 'dragenter', 'dragover', 'drop', 'dragend'];
   $.each(events, function(index, item){
    $lis.on(item, function(e){
     me['_'+item+'Handle'] && me['_'+item+'Handle'](e, me);
    });
   })
   $lis.hover(function(){
    $(this).css('background-color','#eee');
   },function(){
    $(this).css('background-color','#fff');
   });
  },

  //开始拖动
  _dragstartHandle: function(e){
   var me = this,oe = e.originalEvent;
   if(oe.dataTransfer){
    oe.dataTransfer.setData('text', '');
   }
   me.$drag = $(e.currentTarget);
   $('li',me.$el).removeClass('item-hover');
   me.$drag.addClass('draging').siblings().addClass('no-draging');
  },

  _dragenterHandle: function(e){
   var me = this;
   me.$drop = $(e.currentTarget);
   if(me.timer){clearTimeout(me.timer)} //事件控制
   me.timer = setTimeout(function(){
    if(me.$drag.attr('id') !== me.$drop.attr('id')){
     me._createMask();
     if(me.$drag.index()<me.$drop.index()) me.$drag.insertAfter(me.$drop);
     else me.$drag.insertBefore(me.$drop);
    }
   }, 30);

  },

  _dragoverHandle: function(e){
   var oe = e.originalEvent;
   e.preventDefault();
   return false;
  },

  _dropHandle: function(e){
   e.preventDefault();
   e.stopPropagation();
   return false;
  },

  //拖动结束
  _dragendHandle: function(e){
   var me = this;
   me.$mask && me.$mask.remove();
   setTimeout(function(){
    $('li', me.$el).removeClass('draging no-draging');
   },30);
  },

  //创建遮罩
  _createMask: function(){
   var me = this,$mask = me.$mask = $('<div class="drag-mask"></div>');
   $mask.css({
    position: 'absolute',
    width: me.$drop.outerWidth(),//new
    height: me.$drop.outerHeight(),//new
    left: me.$drop.position().left,
    top: me.$drop.position().top+me.$el.scrollTop(),//new
    backgroundColor: '#fff'
   });
   $mask.on({
    'drop': me._dropHandle,
    'dragover': me._dragoverHandle
   });
   this.$el.find('.drag-mask').remove();
   this.$el.append($mask);
  }

 };

 win.Drag = Drag;
})(window);

踩得坑:

1、关于dataTransfer, 事件对象e中是没有该属性的,要找该属性应该通过e.originalEvent.dataTransfer中去找。

2、兼容火狐浏览器。如果不这样操作,火狐下是无法运行的:

if(oe.dataTransfer){
 oe.dataTransfer.setData('text', '');
}

3、dragover事件每隔 350 毫秒会被触发一次。

4、dragstart、dragenter、dragend事件通过jquery绑定,事件处理函数中的this指向最外层对象,例如上面的new Drag();dragover、drop事件通过jquery绑定,事件处理函数中的this指向被绑定的html标签。

5、jquery获取包括padding的宽度调用:$el.outerWidth()$el.outerHeight()

6、只有属性draggable="true"的元素才可以被拖动。

相关推荐