js鼠标拖拽事件

只记录left,top同理。
clientX:返回鼠标相对于浏览器的水平坐标;
offsetLeft:返回当前对象距离浏览器(父对象)的左侧距离;
offsetWidth:对象的可见宽度;
onmousemove:鼠标移动事件;

连接点是鼠标放在div上拖动时的位置(坐标)不会改变的,起名字为unchangX;

鼠标拖动事件是利用position:absolute绝对定位改变left和top,left的位置是通过clientX-unchangeX得到的。

无标题.png
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>鼠标拖拽事件</title>
    <style type="text/css">
        #box{
            width:100px;
            height:100px;
            background-color:cornflowerblue;
            position:absolute;
            left:0;
            top:0;
        }
    </style>
</head>
<body>
    <div id="box"></div>
    <script type="text/javascript">
        window.onload = function(){
            var oDiv = document.getElementById("box"),
                unchangeX = 0,
                unchangeY = 0;
            oDiv.onmousedown =function(ev){//鼠标按下
                var oEvent=ev||event;
                var unchangeX = oEvent.clientX - oDiv.offsetLeft;//鼠标的x坐标减去box的左边距离,unchangeX这个距离是不会变的,通过这个新鼠标的X坐标减去unchangeX就是box的Left
                var unchangeY = oEvent.clientY - oDiv.offsetTop;
                document.onmousemove = function(ev){//为了防止鼠标移动太快而离开了DIV产生了bug,所以要给整个页面加onmousemove事件
                    var oEvent = ev||event;
                    var oLeft = oEvent.clientX - unchangeX;
                    var oTop = oEvent.clientY - unchangeY;
                    //优化部分:鼠标移动到浏览器左侧、右侧、上侧、下侧时的问题
                    if(oLeft < 0){
                        oLeft = 0;
                    }else if(oLeft>document.documentElement.clientWidth - oDiv.offsetWidth){
                        oLeft = document.documentElement.clientWidth - oDiv.offsetWidth;
                    }
                    if(oTop < 0){
                        oTop = 0;
                    }else if(oTop>document.documentElement.clientHeight - oDiv.offsetHeight){
                        oTop = document.documentElement.clientHeight - oDiv.offsetHeight;
                    }
                    oDiv.style.left = oLeft + 'px';
                    oDiv.style.top = oTop + 'px';
                };
                document.onmouseup = function(){//鼠标松开时
                    document.onmousemove = null;//把鼠标移动清除
                    document.onmouseup = null;//把鼠标松开清除
                };
                return false;
            };
        }
    </script>
</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容