高级拖拽库

此库的重点

1.完成拖拽的基本操作

2.清除浏览器拖拽的影响

3.限制范围

(function(w){
    w.$={};
    w.$.drag=function(testNode,callBack){
        //抽象元素一开始的位置
        var startPoint={x:0,y:0};
        //抽象鼠标一开始的位置
        var elementPoint={x:0,y:0};
        
        testNode.onmousedown=function(ev){
            ev = ev||event;
            // debugger
            //设置事件捕获
            if(testNode.setCapture){
                testNode.setCapture();
            }
            // 初始状态是0,0
            startPoint.x = testNode.offsetLeft;
            startPoint.y = testNode.offsetTop;
            
            
            elementPoint.x = ev.clientX;
            elementPoint.y = ev.clientY;
            
            document.onmousemove=function(ev){
                ev = ev||event;
                var nowPoint={x:0,y:0};
                nowPoint.x = ev.clientX;
                nowPoint.y = ev.clientY;
                
                var L = startPoint.x + (nowPoint.x - elementPoint.x );
                // 限制范围
                if(L<0){ 
                    L=0;    
                }else if(L>( testNode.parentNode.clientWidth -testNode.offsetWidth )){
                    L = testNode.parentNode.clientWidth - testNode.offsetWidth;
                }
                
                testNode.style.left=L+"px";
                
                
                if(callBack&&callBack["move"]&& typeof callBack["move"] === "function"){
                    callBack["move"].call(testNode);
                }
            }
            
            document.onmouseup=function(){
                document.onmousemove = document.onmouseup =null;//取消这两个事件
                // 取消事件捕获
                if(document.releaseCapture){
                    document.releaseCapture();
                }
            }
            
            return false;
        }
    }
})(window)

 

posted @ 2020-01-18 17:16  路飞910  阅读(249)  评论(0编辑  收藏  举报