首页 > 其他 > 详细

拖动页面元素,松开释放

时间:2018-10-29 23:17:11      阅读:206      评论:0      收藏:0      [点我收藏+]

嗯哼。不多说,直接上代码了。

  • // 为元素 绑定拖动事件
    function bindDragEvent(obj){
        obj.onmousedown = function(e){
            e = e || window.event;
            
            obj.setCapture && obj.setCapture();    // IE8 及以下 强制捕获下一次单击事件
            
            obj.fixedX = e.clientX - (obj.getBoundingClientRect().left - document.documentElement.clientLeft);
            obj.fixedY = e.clientY - (obj.getBoundingClientRect().top - document.documentElement.clientTop);
            
            document.onmousemove = function(e){
                e = e || window.event;
                
                var x = e.clientX + (document.documentElement.scrollLeft || window.pageXOffset || document.body.scrollLeft);
                var y = e.clientY + (document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop);
                
                obj.style.left = x - obj.fixedX + "px";    // 鼠标在页面中的坐标 - 鼠标在元素内的坐标 = 元素在页面中的坐标
                obj.style.top = y - obj.fixedY + "px";
            };
            
            document.onmouseup = function(){
                document.onmousemove = null;    // 解除 鼠标移动div跟随 事件
                document.onmouseup = null;    // 解除鼠标松开事件
                obj.releaseCapture && obj.releaseCapture();    // IE8 及以下 解除强制捕获单击事件
            };
            
            return false;
        };
    }

     

拖动页面元素,松开释放

原文:https://www.cnblogs.com/tianxiaxuange/p/9873939.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!