萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現 DIV 拖曳移動:滑鼠事件、座標計算、邊界限制完整教學

核心原理

  1. mousedown:記錄滑鼠相對元素的初始偏移
  2. mousemove (綁定 document):計算新位置並更新元素 left/top
  3. mouseup (綁定 document):解除移動事件、恢復游標

基礎版實作

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>jQuery DIV 拖曳範例</title>
  <style>
    .draggable {
      width: 200px; height: 150px;
      background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
      color: white; display: flex; align-items: center; justify-content: center;
      font-size: 18px; font-weight: bold;
      position: absolute; left: 100px; top: 100px; z-index: 100;
      border-radius: 8px; box-shadow: 0 4px 15px rgba(0,0,0,0.2);
      cursor: move; user-select: none;
    }
    .draggable.dragging { box-shadow: 0 8px 25px rgba(0,0,0,0.3); opacity: 0.9; }
  </style>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
  <div class="draggable" id="dragBox">拖曳我!</div>

  <script>
    $(function() {
      const $box = $('#dragBox');
      let offsetX = 0, offsetY = 0;
      let isDragging = false;

      $box.on('mousedown', function(e) {
        // 忽略右鍵、非左鍵
        if (e.which !== 1) return;
        
        isDragging = true;
        const pos = $box.offset();
        offsetX = e.pageX - pos.left;
        offsetY = e.pageY - pos.top;
        $box.addClass('dragging');
        
        // 綁定在 document 上,滑鼠移出元素仍能拖曳
        $(document).on('mousemove.drag', onMouseMove);
        $(document).on('mouseup.drag', onMouseUp);
        
        e.preventDefault(); // 防止文字選取
      });

      function onMouseMove(e) {
        if (!isDragging) return;
        
        const newLeft = e.pageX - offsetX;
        const newTop = e.pageY - offsetY;
        
        $box.css({left: newLeft, top: newTop});
      }

      function onMouseUp() {
        if (!isDragging) return;
        isDragging = false;
        $box.removeClass('dragging');
        $(document).off('.drag'); // 移除命名空間事件
      }
    });
  </script>
</body>
</html>

進階版:邊界限制、吸附、網格對齊

const $box = $('#dragBox');
const $container = $(window); // 或指定容器 $('#container')

const constraints = {
  // 邊界限制
  boundary: 'window', // 'window' | 'parent' | {top, left, right, bottom}
  // 吸附邊緣 (像素)
  snapThreshold: 15,
  // 網格對齊 (像素)
  grid: 20
};

function getBoundary() {
  if (constraints.boundary === 'window') {
    return {
      minX: 0,
      minY: 0,
      maxX: $container.width() - $box.outerWidth(),
      maxY: $container.height() - $box.outerHeight()
    };
  }
  if (constraints.boundary === 'parent') {
    const p = $box.parent();
    return {
      minX: 0,
      minY: 0,
      maxX: p.width() - $box.outerWidth(),
      maxY: p.height() - $box.outerHeight()
    };
  }
  return constraints.boundary; // 自訂物件
}

function applyConstraints(x, y) {
  const b = getBoundary();
  // 限制範圍
  x = Math.max(b.minX, Math.min(x, b.maxX));
  y = Math.max(b.minY, Math.min(y, b.maxY));
  
  // 網格對齊
  if (constraints.grid > 1) {
    x = Math.round(x / constraints.grid) * constraints.grid;
    y = Math.round(y / constraints.grid) * constraints.grid;
  }
  
  // 吸附邊緣
  const snap = constraints.snapThreshold;
  if (Math.abs(x - b.minX) < snap) x = b.minX;
  if (Math.abs(x - b.maxX) < snap) x = b.maxX;
  if (Math.abs(y - b.minY) < snap) y = b.minY;
  if (Math.abs(y - b.maxY) < snap) y = b.maxY;
  
  return {x, y};
}

// 在 onMouseMove 中使用
function onMouseMove(e) {
  if (!isDragging) return;
  const {x, y} = applyConstraints(e.pageX - offsetX, e.pageY - offsetY);
  $box.css({left: x, top: y});
}

觸控裝置支援 (行動裝置)

$box.on('touchstart', function(e) {
  const touch = e.originalEvent.touches[0];
  const pos = $box.offset();
  offsetX = touch.pageX - pos.left;
  offsetY = touch.pageY - pos.top;
  isDragging = true;
  $box.addClass('dragging');
  
  $(document).on('touchmove.drag', onTouchMove);
  $(document).on('touchend.drag touchcancel.drag', onTouchEnd);
  e.preventDefault(); // 防止頁面捲動
});

function onTouchMove(e) {
  if (!isDragging) return;
  const touch = e.originalEvent.touches[0];
  const {x, y} = applyConstraints(touch.pageX - offsetX, touch.pageY - offsetY);
  $box.css({left: x, top: y});
  e.preventDefault();
}

function onTouchEnd() {
  if (!isDragging) return;
  isDragging = false;
  $box.removeClass('dragging');
  $(document).off('.drag');
}

封裝為 jQuery Plugin

(function($) {
  $.fn.draggable = function(options) {
    const defaults = {
      handle: null,           // 拖曳把手 selector,null 為整個元素
      containment: 'window',  // 'window', 'parent', 'document', selector, false
      grid: false,            // [x, y] 或數字
      snap: false,            // 吸附閾值或 selector
      snapMode: 'outer',      // 'outer', 'inner', 'both'
      start: null,            // 回呼 function(event, ui)
      drag: null,             // 回呼 function(event, ui)
      stop: null              // 回呼 function(event, ui)
    };
    
    const opts = $.extend({}, defaults, options);
    
    return this.each(function() {
      const $el = $(this);
      const $handle = opts.handle ? $el.find(opts.handle) : $el;
      let offset = {x: 0, y: 0};
      let dragging = false;
      
      $handle.on('mousedown touchstart', function(e) {
        if (e.which !== 1 && e.type !== 'touchstart') return;
        dragging = true;
        const pos = $el.offset();
        const touch = e.type === 'touchstart' ? e.originalEvent.touches[0] : e;
        offset.x = touch.pageX - pos.left;
        offset.y = touch.pageY - pos.top;
        $el.addClass('ui-draggable-dragging');
        
        const ui = {helper: $el, position: $el.position(), offset: $el.offset()};
        if (opts.start) opts.start.call($el[0], e, ui);
        
        $(document).on('mousemove.drag touchmove.drag', moveHandler);
        $(document).on('mouseup.drag touchend.drag touchcancel.drag', upHandler);
        e.preventDefault();
      });
      
      function moveHandler(e) {
        if (!dragging) return;
        const touch = e.type === 'touchmove' ? e.originalEvent.touches[0] : e;
        let left = touch.pageX - offset.x;
        let top = touch.pageY - offset.y;
        
        // containment 處理略...
        // grid/snap 處理略...
        
        $el.css({left, top});
        const ui = {helper: $el, position: {left, top}, offset: $el.offset()};
        if (opts.drag) opts.drag.call($el[0], e, ui);
      }
      
      function upHandler(e) {
        if (!dragging) return;
        dragging = false;
        $el.removeClass('ui-draggable-dragging');
        $(document).off('.drag');
        const ui = {helper: $el, position: $el.position(), offset: $el.offset()};
        if (opts.stop) opts.stop.call($el[0], e, ui);
      }
    });
  };
})(jQuery);

// 使用
$('#dragBox').draggable({
  containment: 'window',
  grid: 20,
  snap: 15,
  start: (e, ui) => console.log('開始拖曳'),
  drag: (e, ui) => $('#pos').text(`X: ${ui.position.left}, Y: ${ui.position.top}`),
  stop: (e, ui) => console.log('結束位置', ui.position)
});

效能優化建議

  • 使用 requestAnimationFrame 節流 mousemove 更新
  • 避免在 drag 回呼中執行重度運算
  • 大量可拖曳元素時,考慮事件代理或 IntersectionObserver
  • CSS will-change: transform 提示瀏覽器優化

總結

jQuery 拖曳核心在於三個事件的協作:mousedown 記錄偏移 → document.mousemove 計算新座標 → document.mouseup 清理。進階功能 (邊界、吸附、網格、觸控、Plugin 封裝) 皆在此架構上擴充。現代專案若無 jQuery 依賴,建議使用原生 Drag and Drop API 或輕量函式庫 (如 InteractJS)。

copyright © 萬盛學電腦網 all rights reserved