Fork me on GitHub

Jquery拖拽原理

/*
onmousedown : 选择元素
onmousemove : 移动元素
onmouseup : 释放元素
*/

查看Demo:拖拽图片

    function drag(obj) {
        
        obj.onmousedown = function(ev) {
            var ev = ev || event;
            
            var disX = ev.clientX - this.offsetLeft;
            var disY = ev.clientY - this.offsetTop;
            
            if ( obj.setCapture ) {
                obj.setCapture();
            }
            
            document.onmousemove = function(ev) {
                var ev = ev || event;
                
                obj.style.left = ev.clientX - disX + 'px';
                obj.style.top = ev.clientY - disY + 'px';
            }
            
            document.onmouseup = function() {
                document.onmousemove = document.onmouseup = null;
                //释放全局捕获 releaseCapture();
                if ( obj.releaseCapture ) {
                    obj.releaseCapture();
                }
            }
            
            return false;
            
        }
        
    }

 

posted on 2015-01-24 13:14  雨为我停  阅读(676)  评论(0编辑  收藏  举报