拖拽(兼容版)

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title></title>
    </head>
    <body>
        <div id="box1"></div>
        <div id="box2"></div>
    </body>
    <script type="text/javascript">
        // 开启拖拽
        // 获取box1
        var box1 = document.getElementById("box1");
        // 给box1绑定一个鼠标鼠标按下事件
        drag(box1);
        
        var box2 = document.getElementById("box2");
        drag(box2);
        
        // 拖拽的方法
        function drag(obj) {
            // 当鼠标在被拖拽元素上被按下时,开始拖拽 (onmousedown)
            obj.onmousedown = function(event){
                
                // 设置obj捕获所有鼠标按下事件(针对IE8兼容问题)( 'setCapture()&releaseCapture()' 只有IE浏览器识别)
                // obj.setCapture && obj.setCapture();
                if(obj.setCapture){
                    obj.setCapture();
                }
                
                event = event || window.event;
                // div 的右偏移量 = 鼠标.clientX - obj.offsetLeft
                // div 的上偏移量 = 鼠标.clientY - obj.offsetTop
                var ol = event.clientX - obj.offsetLeft;
                var ot = event.clientY - obj.offsetTop;
                
                // 为document绑定一个onmousemove事件
                document.onmousemove = function(event){
                    event = event || window.event;
                    // 当鼠标移动时,被拖拽的元素随鼠标移动 onmousemove
                    
                    // ********获取鼠标坐标
                    var left = event.clientX - ol;
                    var top = event.clientY - ot;
                    
                    // 修改obj的定位
                    obj.style.left = left + "px";
                    obj.style.top = top + "px";
                    
                    // 为被拖拽元素绑定一个鼠标松开事件
                    document.onmouseup = function(){
                        // 当鼠标松开时,被拖拽元素固定在当前位置 onmouseup
                        // 取消document的onmousemove事件
                        document.onmousemove = null;
                        // 取消document的onmouseup事件
                        document.onmouseup = null;
                        // 当鼠标松开时,取消对事件的捕获
                        // obj.releaseCapture && obj.releaseCapture();
                        if(obj.releaseCapture){
                            obj.releaseCapture();
                        }
                    }
                }
                return false; // 取消浏览器默认行为(除IE8)
            }
        }
    </script>
    <style>
        #box1 {
            width: 100px;
            height: 100px;
            background-color: blue;
            position: absolute;
        }
        #box2 {
            width: 100px;
            height: 100px;
            background-color: #f00;
            position: absolute;
            top: 100px;
            left: 100px;
        }
    </style>
</html>

 

posted @ 2019-04-03 14:47  资壁史卧边羌  阅读(196)  评论(0编辑  收藏  举报