基于jquery的鼠标拖拽

455 阅读1分钟

//2017-11-01

基于jquery的鼠标拖拽

//鼠标拖拽

$.fn.mouseDrag = function(options){
    var $this = $(this);
    if(!$this.length){return $this;}
    var opts = $.extend({
        target:null,
        startCallback:null,
        moveCallback:null,
        endCallback:null
    },options);
    var startInfo = null;
    var moveInfo = null;
    var targetNode = null;
    //获取xy
    function getXY(e){
        return {
            x : Math.ceil(e.pageX || e.clientX),
            y : Math.ceil(e.pageY || e.clientY)
        }
    };

    //鼠标移动事件
    var mouseMove = function(e){
        var e = e || window.event;
        var moveXY = getXY(e);
        moveInfo = {
            startXY:startInfo.xy,
            xy : moveXY,
            offsetXY : {
                x : moveXY.x - startInfo.xy.x,
                y : moveXY.y - startInfo.xy.y
            }

        }
        if(typeof opts.moveCallback == 'function'){
            opts.moveCallback.call(targetNode,moveInfo);
        };
        return false;
    };
    //鼠标抬起解绑事件
    var mouseUp = function(e){
        if(typeof opts.endCallback == 'function'){
            opts.endCallback.call(targetNode,moveInfo);
        };
        $(document).off('mousemove',mouseMove);
        $(document).off('mouseup',mouseUp);
        moveInfo = null;
        startInfo = null;
        targetNode = null;
        return false;
    }
    //鼠标按下
    function mouseDown(e){
        var e = e || window.event;
        startInfo = {
            xy: getXY(e)
        };
        targetNode = this;
        if (typeof opts.startCallback == 'function') {
            opts.startCallback.call(targetNode, startInfo);
        }
        $(document).on('mousemove', mouseMove);
        $(document).on('mouseup', mouseUp);
        return false;
    }
    //鼠标按下监听事件
    if(opts.target){
        $this.on('mousedown',opts.target,mouseDown);
    }else{
        $this.on('mousedown',mouseDown);
    }
    
    return $this;
};