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

通常弹框都是固定居中(或顶部、底部)显示的,最近碰到了这样的考题,以为有趣,因此记录下来。css

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

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

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

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

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便可。it

多年之前,刚会点js,作过一样的功能,写得巨复杂,反复改了好久。如今梳理下,其实很简单,这就是进步吧,哈哈!io

相关文章
相关标签/搜索