DIV CSS 佈局教程網

自己封裝的原生 JS 拖曳方法:邊界限制與拖動點分離
編輯:關於JavaScript     

拖曳功能乍看簡單,實際寫起來會遇到幾個不直觀的問題:滑鼠移太快時會「掉開」、拖到視窗外元素會跑掉、拖動區域想跟可視範圍分離(例如只讓標題列可以拖)。下面這個 drag 函式把這些都處理完了。

程式碼

function drag(t, p){
  var point    = p || null,     // 拖動點
      target   = t || null,     // 被拖動的元素
      resultX  = 0,
      resultY  = 0;

  (!point) ? point = target : '';   // 沒指定拖動點時,整個元素都可拖

  // 累加 offsetParent 鏈,取得元素相對於文件的絕對位置
  function getPos(t){
    var offsetLeft = 0, offsetTop = 0, offsetParent = t;
    while (offsetParent) {
      offsetLeft += offsetParent.offsetLeft;
      offsetTop  += offsetParent.offsetTop;
      offsetParent = offsetParent.offsetParent;
    }
    return { 'top': offsetTop, 'left': offsetLeft };
  }

  function core(){
    var width  = document.body.clientWidth  || document.documentElement.clientWidth,
        height = document.body.clientHeight || document.documentElement.clientHeight;

    maxWidth  = width  - target.offsetWidth;
    maxHeight = height - target.offsetHeight;

    // 視窗尺寸變化時,把元素位置夾回合法範圍
    (resultX >= maxWidth) ? target.style.left = maxWidth + 'px'
      : (resultX > 0) ? target.style.left = resultX + 'px' : '';
    (resultY >= maxHeight) ? target.style.top = maxHeight + 'px'
      : (resultY > 0) ? target.style.top = resultY + 'px' : '';

    point.onmousedown = function(e){
      var e     = e || window.event,
          coordX = e.clientX, coordY = e.clientY,
          posX   = getPos(target).left,
          posY   = getPos(target).top;

      point.setCapture && point.setCapture();   // 把 Mouse 事件鎖定在拖動點上

      document.onmousemove = function(e){
        var ev    = e || window.event,
            moveX = ev.clientX, moveY = ev.clientY;

        // 結果座標 = 目前游標 - 游標在元素內的偏移量
        resultX = moveX - (coordX - posX);
        resultY = moveY - (coordY - posY);

        (resultX > 0)
          ? ((resultX < maxWidth) ? target.style.left = resultX + 'px'
                                   : target.style.left = maxWidth + 'px')
          : target.style.left = '0px';

        (resultY > 0)
          ? ((resultY < maxHeight) ? target.style.top = resultY + 'px'
                                    : target.style.top = maxHeight + 'px')
          : target.style.top = '0px';

        ev.stopPropagation && ev.stopPropagation();
        ev.preventDefault;
        ev.returnValue = false;
        ev.cancelBubble = true;
      };
    };

    document.onmouseup = function(){
      // 避免游標停在非拖動點的元素上時,無法觸發 onmouseup 的問題
      document.onmousemove = null;
      point.releaseCapture && point.releaseCapture();
    };

    point.onmouseup = function(e){
      document.onmousemove = null;
      point.releaseCapture && point.releaseCapture();
    };
  }

  core();
  window.onresize = core;
}

使用方式

drag(t, p)
/*
 * t:被拖動的元素
 * p:拖動點(可省略,省略時整個元素都可拖)
 */

幾個關鍵設計說明

coordX - posX 是整段程式碼最容易被忽略但最重要的一行。它算的是「游標下載點距離元素左上角有多遠」。如果直接把 clientX 當成元素的 left,那滑鼠一按下去元素就會跳到左上角;減掉這個偏移量之後,元素才會「乖乖地」跟著游標移動,維持原本的抓取位置。

setCapture() 是另一個重點。滑鼠移動速度快時,游標可能在兩次 mousemove 之間跑出元素範圍,事件就不再由元素接收,拖曳看起來就像「卡住」或「掉開」。把指標事件鎖定在拖動點上,就保證整個拖曳過程中事件都會送達。這組 API 在標準瀏覽器已更名為 setPointerCapture,如果要支援新環境建議改用指標事件版本。

把 mousemove 綁在 document 而不是元素上,是為了讓游標移動到任何位置都能持續追蹤;而 onmouseup 同時掛在 document 與 point 上,則是為了兼容不同瀏覽器的事件觸發順序差異。

兩個可以改進的地方

第一,maxWidth 與 maxHeight 沒有宣告,會變成全域變數。加上 var 是基本衛生。

第二,ev.preventDefault; 這行少了括號,實際上只是讀取了函式本身而沒有呼叫它,等於什麼都沒做。真正阻止預設行為的是下面兩行(returnValue = false 與 cancelBubble = true),所以功能不受影響,但這行應該刪掉或補成 ev.preventDefault && ev.preventDefault();。

以上就是這個原生 JS 拖曳方法的完整實作,核心觀念是「記錄抓取偏移量」加「鎖定指標事件」,掌握這兩點,之後要加上多點觸控或慣性移動都會容易很多。

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