DIV CSS 佈局教程網

JavaScript 完美拖拽實作:邊界判斷與事件綁定
編輯:關於JavaScript     

拖拽看起來神奇,原理其實只有一句話:讓元素跟著滑鼠走。真正的細節在於「不要讓滑鼠跳到元素中心」以及「不要把元素拖出畫面」。本文完整拆解。

三個核心觀念

一、算出滑鼠與元素的相對偏移。按下滑鼠時,記錄 滑鼠座標 - 元素 offsetLeft/Top,這個差值在整個拖曳過程中保持不變,元素才不會突然跳到滑鼠位置。

二、為什麼 mousemove 要掛在 document 上。滑鼠移動很快,如果監聽掛在元素本身,游標一旦移出元素範圍就收不到事件,拖拽會中斷。掛在 document 上則永遠能收到。

三、邊界判斷。拖到視窗外會看不到元素,所以上下左右都要夾住。

HTML 與 CSS

<div id="div1"></div>
#div1 { width:100px; height:100px; background:red; position:absolute; }

JavaScript

window.onload = function() {
  var oDiv = document.getElementById("div1");
  var x = 0, y = 0;

  oDiv.onmousedown = function(ev) {
    var oEvent = ev || event;

    // 記下滑鼠與元素左上角的距離
    x = oEvent.clientX - oDiv.offsetLeft;
    y = oEvent.clientY - oDiv.offsetTop;

    document.onmousemove = function(ev) {
      var oEvent = ev || event;
      var left  = oEvent.clientX - x;
      var right = oEvent.clientY - y;

      // 左右邊界
      if (left < 0) {
        left = 0;
      } else if (left > document.documentElement.clientWidth - oDiv.offsetWidth) {
        left = document.documentElement.clientWidth - oDiv.offsetWidth;
      }

      // 上下邊界
      if (right < 0) {
        right = 0;
      } else if (right > document.documentElement.clientHeight - oDiv.offsetHeight) {
        right = document.documentElement.clientHeight - oDiv.offsetHeight;
      }

      oDiv.style.left = left + "px";
      oDiv.style.top  = right + "px";
    };

    document.onmouseup = function() {
      // 放開滑鼠後清除事件,避免元素黏在游標上
      document.onmousemove = null;
      document.onmouseup = null;
    };

    return false; // 避免選取到文字或觸發原生拖曳
  };
};

幾個容易出錯的地方

邊界要用「容器尺寸減去元素尺寸」。只判斷 left < 0 是不夠的,右邊界必須扣掉元素寬度,否則會有一半跑出畫面。原範例中判斷下邊界時誤寫成 document.documentElenment(拼字錯誤),上面已修正。

記得 return false。不阻止預設行為,在 Firefox 等瀏覽器可能觸發原生的元素拖曳或文字選取,造成游標閃動。

用 pointer events 更好。現在推薦改用 pointerdown/pointermove/pointerup,並搭配 setPointerCapture,同一套程式就能同時支援滑鼠、觸控與手寫筆,也不必再手動判斷 ev || event。

可訪問性別忘了。純滑鼠的拖拽對鍵盤使用者毫無用處,建議同時提供方向鍵移動的支援,並加上 role="button" 與 tabindex。

以上就是拖拽效果的完整實作與注意事項。

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