DOM元素四向拖動的基本實現 原

一般彈框都是固定居中(或頂部、底部)顯示的,最近碰到了這樣的考題,覺得有趣,所以記錄下來。

首先,假定我們拖動一個藍色的方塊:

#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,做過同樣的功能,寫得巨複雜,反覆改了很久。現在梳理下,其實很簡單,這就是進步吧,哈哈!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章