DIV CSS 佈局教程網

原生 JS 元素拖曳:處理位移與 click 衝突
編輯:關於JavaScript     

拖曳效果的核心不難:在 mousedown 記下起點與元素目前的偏移量,在 mousemove 時把滑鼠座標減去那個差值,就得到元素的新位置,最後在 mouseup 收掉監聽。

真正麻煩的是一個附帶問題:拖完之後,click 事件還是會照常觸發。使用者只是想搬家,卻不小心點亮了元素的背景色——這種小毛病最容易讓人懷疑自己寫錯了什麼。

// 宿主為瀏覽器;把要拖曳的元素參照傳進來
function candrag(drager) {

    drager.onmousedown = function (down) {

        var offx = drager.offsetLeft;
        var offy = drager.offsetTop;

        // 滑鼠位置與元素左上角之間的差距,拖曳過程中必須保持不變
        var offxl = down.clientX - offx;
        var offyl = down.clientY - offy;

        // 在 window 上掛一個旗標,用來跟 click 事件溝通
        window.condition = 0;

        document.onmousemove = function (move) {
            drager.style.left = move.clientX - offxl + "px";
            drager.style.top  = move.clientY - offyl + "px";
            drager.style.cursor = "move";

            // 總位移量:橫向與縱向移動距離相加
            condition = Math.abs(move.clientX - down.clientX)
                      + Math.abs(move.clientY - down.clientY);
        };
    };

    drager.onmouseup = function () {
        document.onmousemove = null;
        drager.style.cursor = "auto";
    };
}

/*
 * 在 click 裡判斷 condition 是否為 0,就能分辨「純點擊」與「拖曳後放手」
 *
 * 例如:
 *   candrag(dragger);
 *   d01.onclick = function () {
 *       if (!condition) {
 *           d01.style.backgroundColor = "red";
 *       }
 *   }
 *
 * 其中 d01 為 dragger 的子元素
 */

幾個值得改進的地方

變數請用閉包,不要掛在 window 上。把 condition 放在全域,一旦頁面上有兩組拖曳元件就會互相干擾。改寫成 function 內的區域變數,再透過回傳一組方法存取,才是安全做法。

拖曳起點的閾值用 3~5px 比較自然。只要手指或滑鼠有半點抖動就判定為拖曳,體驗會很糟。加一個最小位移門檻,超過才算拖動,click 也才跟著被抑制。

記得鎖定 position。程式碼裡設定了 left 與 top,但元素的 position 必須是 absolute 或 relative,否則這兩個值根本不生效——這是最常見的「拖不動」原因。

mouseup 建議掛在 document 上。目前寫在 drager 身上,若使用者在快速移動中於元素外放手,監聽不會被清掉,元素就會黏著滑鼠。把 mouseup 也掛到 document,並補上 mouseleave 的保險,會穩得多。

行動裝置要另寫一套。觸控裝置沒有 mousemove,得改用 touchstart / touchmove / touchend,並從 event.touches[0] 取座標;同時要在 touchmove 裡呼叫 preventDefault,否則拖曳的同時頁面也會跟著捲動。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved