js实现简单拖拽案例

简单拖拽事件主要是监听三个事件:onmousedown, onmousemove, onmouseup 三个事件,思路也很简单,但是写的时候还是遇到了一些小问题,先放代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>拖拽事件案例</title>
    <style type="text/css">
        *{
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        #div{
            width: 100px;
            height: 100px;
            position: relative;
            left: 0;
            top: 0;
            background: #00a9e2;
            font-size: 28px;
            color: #fff;
            text-align: center;
            line-height: 100px;
        }
    </style>
</head>
<body>
    <div id="div">
        拖拽
    </div>
</body>
<script>
    var div = document.getElementById('div');
    div.onmousedown = function (e) {
        var startX = div.offsetLeft;
        var startY = div.offsetTop;
        var downX = e.clientX;
        var downY = e.clientY;
        document.onmousemove = function (e) {
            var moveX = e.clientX;
            var moveY = e.clientY;
            div.style.left = (startX + moveX - downX) + 'px';
            div.style.top = (startY + moveY - downY) + 'px';
        };
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;
        }
    };
</script>
</html>

说一下遇到的小问题:
1,开始没有获取startX,startY, 当第一次拖拽时正常,但是第二次就有问题了,点击后直接返回初始位置了,所以我们每次onmousedown时应该先获取startX,startY,在赋值拖拽位置时要加上
2,document.onmouseup写在了onmousedown函数的外面了,只能触发一次,第二次点击时,元素便不能停止拖拽了
3,注意offsetLeft,offsetTop是获取元素相对于元素最近有定位的父元素的left,top ,没有定位的父元素,则是获取相对于body的
4,clientX(Y) 事件属性返回当事件被触发时鼠标指针向对于浏览器页面(或客户区)的水平坐标(垂直坐标)

猜你喜欢

转载自blog.csdn.net/wangcuiling_123/article/details/78447404
今日推荐