用mouse事件写一个可拖拽的div

文章目录


<!DOCTYPE html>
<html>

<head>
    <title>用mouse事件写一个可拖拽的div</title>
    <style type="text/css">
        #div1 {
            position: absolute;
            width: 200px;
            height: 200px;
            background: pink;
        }
    </style>
</head>

<body>
    <p>
        <label for="refer"></label>
        <a id="refer" href="https://blog.csdn.net/github_38861674/article/details/77618957">用鼠标事件实现拖拽</a>
    </p>

    <div id="div1"></div>

    <script type="text/javascript">
        window.onload = function () {
            var moveBox = document.getElementById('div1');
            var windowH = window.innerHeight,
                windowW = window.innerWidth;
            // 当鼠标在moveBox里面按下时
            moveBox.onmousedown = function (event) {
                event = event || window.event;
                var distanceX = event.clientX - this.offsetLeft,
                    distanceY = event.clientY - this.offsetTop;
                // 当鼠标在document任意位置时,连续触发    
                document.onmousemove = function (event_2) {
                    event_2 = event_2 || window.event;
                    /*clientX,clientY鼠标的x,y坐标*/
                    var left = event_2.clientX - distanceX,
                        top = event_2.clientY - distanceY;
                    if (left < 0) left = 0;
                    if (top < 0) top = 0;
                    /*offsetWith,offsetHeight控件的高度,宽度*/
                    if (left > windowW - moveBox.offsetWidth) left = windowW - moveBox.offsetWidth;
                    if (top > windowH - moveBox.offsetHeight) top = windowH - moveBox.offsetHeight;
                    moveBox.style.left = left + 'px';
                    moveBox.style.top = top + 'px'
                    // 当鼠标离开时,移除鼠标移动事件;
                    document.onmouseup = function () {
                        document.onmousemove = null;
                        document.onmouseup = null;
                    }
                }
            }
        }
    </script>

</body>

</html>

运行效果:
在这里插入图片描述

发布了231 篇原创文章 · 获赞 93 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/wobushixiaobailian/article/details/103316219