DIV CSS 佈局教程網

打造自己的拖曳插件:邊界、選取與圖片預設行為一次處理
編輯:JavaScript綜合知識     

最初的目標很單純:在頁面上拖動一些小圓點做定位標記,然後複製 HTML 貼到開發程式碼裡。這個功能實作了無數次都做不好,最後只好用外掛。直到把幾個關鍵細節想通,才終於完成。

設計思路:事件綁在哪裡

$target.bind('mousedown', fn);
$(document)
  .bind('mousemove', fn)
  .bind('mouseup', fn);

三個事件不該都綁在拖曳元素上。滑鼠移動太快時,游標可能瞬間移出元素範圍,此時 mousemove 與 mouseup 都不會觸發,元素就會卡在「拖曳中」狀態永遠放不掉。綁在 document 上,事件一定收得到。

細節一:阻止文字被選中

// 阻止區域文字被選中(chrome、firefox、ie9+)
e.preventDefault();

// for firefox、ie9 或更早
window.getSelection ? window.getSelection().removeAllRanges()
                    : document.selection.empty();

拖曳時滑過文字會產生藍色選取,看起來很糟。preventDefault 處理現代瀏覽器,document.selection.empty() 則是 IE 專屬的相容寫法。另外在 CSS 上對拖曳元素設 user-select: none 可以從源頭避免。

細節二:圖片的預設拖曳

e.preventDefault();

若拖曳元素是 img,拖一小段距離會出現「禁止」游標與半透明殘影——這是瀏覽器原生的圖片拖放行為。preventDefault 就能阻止。另一個做法是把 img 設為 pointer-events: none,或加上 draggable="false"。

細節三:邊界處理

一開始這樣寫:

// x、y 是拖曳元素將要設定的 left、top,limitObj 是拖曳範圍
if (x >= limitObj._left && x <= limitObj._right) {
  $target.css({ left: x + 'px' });
}
if (y >= limitObj._top && y <= limitObj._bottom) {
  $target.css({ top: y + 'px' });
}

測試時發現元素常常貼不到邊界。原因是 x 一旦超出範圍,整個 if 不成立,位置就完全不更新,於是元素停在上一個合法位置,離邊界還有一大截。

正確做法是把超出範圍的值夾回邊界,而非放棄更新:

if (x < limitObj._left)  x = limitObj._left;
if (x > limitObj._right) x = limitObj._right;
if (y < limitObj._top)   y = limitObj._top;
if (y > limitObj._bottom) y = limitObj._bottom;

$target.css({ left: x + 'px', top: y + 'px' });

有人給出了更簡潔的寫法:

$target.css({
  left: Math.max(Math.min(x, limitObj._right), limitObj._left) + 'px',
  top:  Math.max(Math.min(y, limitObj._bottom), limitObj._top) + 'px'
});

內層 Math.min 先封住上界,外層 Math.max 再封住下界,一行搞定,不必寫四個 if。

完整插件

$.fn.extend({
  drag: function (options) {
    var dragStart, dragMove, dragEnd, $boundaryElem, limitObj;

    function _initOptions() {
      var noop = function () {};
      var defaultOptions = {
        boundaryElem: 'body'        // 邊界容器
      };
      options = $.extend(defaultOptions, options || {});
      $boundaryElem = $(options.boundaryElem);
      dragStart = options.dragStart || noop;
      dragMove  = options.dragMove  || noop;
      dragEnd   = options.dragEnd   || noop;
    }

    function _drag(e) {
      var $target = $(this), self = this;
      limitObj = {
        _left: 0, _top: 0,
        _right:  ($boundaryElem.innerWidth()  || $(window).width())  - $target.outerWidth(),
        _bottom: ($boundaryElem.innerHeight() || $(window).height()) - $target.outerHeight()
      };

      // 記錄滑鼠按下時的位置與元素的相對位置
      var clientX = e.clientX, clientY = e.clientY;
      var offsetLeft = this.offsetLeft, offsetTop = this.offsetTop;

      dragStart.apply(this, arguments);

      $(document).bind('mousemove', moveHandle).bind('mouseup', upHandle);

      function moveHandle(e) {
        var x = e.clientX - clientX + offsetLeft;
        var y = e.clientY - clientY + offsetTop;

        $target.css({
          left: Math.max(Math.min(x, limitObj._right),  limitObj._left) + 'px',
          top:  Math.max(Math.min(y, limitObj._bottom), limitObj._top)  + 'px'
        });

        dragMove.apply(self, arguments);
        e.preventDefault();     // 阻止圖片原生拖曳
      }

      function upHandle(e) {
        $(document).unbind('mousemove', moveHandle);
        dragEnd.apply(self, arguments);
      }
    }

    _initOptions();

    $(this)
      .css({ position: 'absolute' })
      .each(function () {
        $(this).bind('mousedown', function (e) {
          _drag.apply(this, [e]);
          e.preventDefault();
          window.getSelection ? window.getSelection().removeAllRanges()
                              : document.selection.empty();
        });
      });

    return this;                // 保持鏈式呼叫
  }
});

呼叫方式

(function () {
  $('.drag-elem').drag({
    boundaryElem: '#boundary',
    dragStart: function () {
      $(this).html('<span>準備拖動</span>')
             .css({ zIndex: 2 }).siblings().css({ zIndex: 1 });
    },
    dragMove: function () {
      var pos = $(this).position();
      $(this).html('<span>拖動中(' + pos.left + ',' + pos.top + ')</span>');
    },
    dragEnd: function () {
      $(this).html('<span>拖動結束</span>');
    }
  });
}());

看懂原理之後

整個流程就是:mousedown 時把移動事件轉移到 document,靠滑鼠在 document 上的位移來推算元素該去的位置;mouseup 時解除綁定。另外有個小技巧——用全域的 left、top 記錄上一次滑鼠的位置,本次位置減去它就是位移量,累加到元素位置上即可。

想改成「拖曳調整大小」也一樣,在 moveHandle 裡改寬高就好。

今天會怎麼重寫

用 Pointer Events 取代滑鼠事件,一次支援滑鼠、觸控與手寫筆:

el.addEventListener('pointerdown', function (e) {
  el.setPointerCapture(e.pointerId);        // 自動處理游標移出元素的問題
  // ...
});
el.addEventListener('pointermove', move);
el.addEventListener('pointerup', end);

用 transform: translate() 而非 left / top 來位移,可以只觸發合成而不觸發重排,流暢度差距明顯。CSS 上加 touch-action: none 避免觸控裝置上的頁面跟著捲動。最後別忘了 ESC 鍵取消拖曳,以及 aria-grabbed 這類無障礙屬性——原版的 delegate 寫法在 jQuery 3 中也已改為 on。

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