DOM元素四向拖动的基本实现

原创
2016/07/28 16:10
阅读数 192

一般弹框都是固定居中(或顶部、底部)显示的,最近碰到了这样的考题,觉得有趣,所以记录下来。

首先,假定我们拖动一个蓝色的方块:

#box {
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: blue;
}

当鼠标左键按下时,它进入可拖动状态,然后随着鼠标移动而移动,当鼠标松开时,停止移动。

用到的事件是mousedownmousemovemouseup,代码如下:

function movingbox(elem) {
    var moving = false;
    var x, y;
    elem.onmousedown = function(e) {
        moving = true;
        // 因为css里没定义left和top,所以初始置0,避免其跳到左上角
        x = elem.style.left ? e.pageX - parseInt(elem.style.left) : 0;
        y = elem.style.top ? e.pageY - parseInt(elem.style.top) : 0;
        elem.style.cursor = 'move';
    };
    // 侦听document的mousemove和mouseup事件,这样当鼠标快速移动时,也能正确响应
    document.addEventListener('mousemove', function(e) {
        if (moving) {
            elem.style.left = e.pageX - x + 'px';
            elem.style.top = e.pageY - y + 'px';
        }
    }, false);
    document.addEventListener('mouseup', function() {
        if (moving) {
            moving = false;
            elem.style.cursor = 'inherit';
        }
    }, false);
}

movingbox(document.getElementById('box'));

对于触屏设备,将相应的事件换成touchstarttouchmovetouchend即可。

多年以前,刚会点js,做过同样的功能,写得巨复杂,反复改了很久。现在梳理下,其实很简单,这就是进步吧,哈哈!

展开阅读全文
加载中
点击引领话题📣 发布并加入讨论🔥
0 评论
1 收藏
0
分享
返回顶部
顶部