1. 程式人生 > >實現容器內部拖拽 ---- drag.js

實現容器內部拖拽 ---- drag.js

上一篇文章介紹了 sortable.js 實現拖拽,這裡在介紹一種實現拖拽的方法

話不多說直接上程式碼

<!DOCTYPE html>
<HTML>
<HEAD>
	<meta http-equiv="content-type" content="text/html; charset=UTF-8">
	<link rel="stylesheet" href="./css/zTreeStyle/zTreeStyle.css" />
	<script src="./js/jquery-1.4.4.min.js"></script>
	<script src="./js/drag.js"></script>
</HEAD>
 <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>
<BODY>
	<ul class="drag-box" style="width: 300px;">
	</ul>
<script type="text/javascript">
	    new Drag({
	        container: '.drag-box',
	        data: ['應用1','應用2','應用3','應用4','應用5','應用6','應用7','應用8','應用9']
	    });
	</script>
</BODY>
</HTML>

附上 drag.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.bind(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.bind({
                'drop': me._dropHandle,
                'dragover': me._dragoverHandle
            });
            this.$el.find('.drag-mask').remove();
            this.$el.append($mask);
        }

    };

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