DIV CSS 佈局教程網

jQuery 拖曳原理拆解:三個事件就夠
編輯:JQuery特效代碼     

拖曳看起來神奇,原理其實只有三個狀態要管。

<style>
#drag {
  width: 400px; height: 300px; cursor: move;
  position: absolute; top: 100px; left: 100px; border: solid 1px #ccc;
}
</style>

<script type="text/javascript">
$(function () {
  /* 拖曳原理
   * 以 dragging 標記拖曳狀態,iX / iY 記錄起始座標
   * mousedown:dragging = true,記錄起始位置,設定滑鼠捕獲
   * mousemove:dragging 為 true 時,目前座標 - 起始座標 = 位移量
   * mouseup:dragging = false,釋放捕獲並阻止冒泡
   */
  var dragging = false;
  var iX, iY;

  $("#drag").mousedown(function (e) {
    dragging = true;
    iX = e.clientX - this.offsetLeft;
    iY = e.clientY - this.offsetTop;
    this.setCapture && this.setCapture();
    return false;
  });

  document.onmousemove = function (e) {
    if (dragging) {
      e = e || window.event;
      var oX = e.clientX - iX;
      var oY = e.clientY - iY;
      $("#drag").css({ "left": oX + "px", "top": oY + "px" });
      return false;
    }
  };

  $(document).mouseup(function (e) {
    dragging = false;
    $("#drag")[0].releaseCapture();
    e.cancelBubble = true;
  });
})
</script>

<div id="drag"><h2>來拖動我啊</h2></div>

關鍵在那個差值

許多人會直接寫 left = e.clientX,結果元素左上角會「黏」到滑鼠,跳一下才開始拖。正解是先記下 滑鼠位置 - 元素目前 left 這個差值 iX,之後每次移動都用「目前滑鼠位置 - iX」當新的 left。這樣不管你從元素的哪個位置按下,拖曳手感都一致。

另外元素必須是 position:absolute(或 relative)才能用 left/top 定位;mousedown 回傳 false 是為了避免拖曳時把文字選取起來。現代寫法可用 pointerdown/pointermove/pointerup 搭配 setPointerCapture,滑鼠與觸控就能共用同一套邏輯。

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