DIV CSS 佈局教程網

jQuery 拖曳改變元素大小的原型實作
編輯:JQuery常見問題     

效果說明

按住灰色方塊拖曳,就能像拉動視窗邊角一樣改變它的寬高。整個功能不到五十行,沒有使用任何外掛,是理解「拖曳」本質的好例子。

效果體驗:https:///keleyi/phtml/jqtexiao/29.htm

拖曳的三個步驟

  1. mousedown:按下時先記住滑鼠座標與元素尺寸的差值 x、y,這個偏移量是後續計算的基準。
  2. mousemove:移動時用當前座標減去偏移量,直接寫成新的 width/height。
  3. mouseup:放開時解除 mousemove 與 mouseup 的綁定,避免滑鼠離開後仍在縮放。
$(function () {
  bindResize(document.getElementById('kel' + 'eyi'));
});

function bindResize(el) {
  var els = el.style,
      x = y = 0;

  $(el).mousedown(function (e) {
    // 記下滑鼠位置與元素尺寸的差
    x = e.clientX - el.offsetWidth,
    y = e.clientY - el.offsetHeight;

    el.setCapture ? (
      el.setCapture(),
      el.onmousemove = function (ev) { mouseMove(ev || event) },
      el.onmouseup = mouseUp
    ) : (
      $(document).bind("mousemove", mouseMove).bind("mouseup", mouseUp)
    );

    e.preventDefault()   // 避免選取文字等預設行為
  });

  function mouseMove(e) {
    els.width  = e.clientX - x + 'px';
    els.height = e.clientY - y + 'px';
  }

  function mouseUp() {
    el.releaseCapture ? (
      el.releaseCapture(),
      el.onmousemove = el.onmouseup = null
    ) : (
      $(document).unbind("mousemove", mouseMove).unbind("mouseup", mouseUp)
    );
  }
}

樣式設定

#keleyi{
  position:absolute;
  top:0; left:0;
  width:200px; height:100px;
  background:#f1f1f1;
  text-align:center;
  line-height:16px;
  border:1px solid #CCC;
  cursor:move;
}

幾個實作細節

  • setCapture()/releaseCapture() 是 IE 的滑鼠捕捉機制,能讓元素在滑鼠移出自身範圍後仍持續收到事件;其他瀏覽器則改用把事件綁在 document 上的折衷方案。兩條路徑並存,就是為了跨瀏覽器相容。
  • e.preventDefault() 是必要的,否則拖曳時會把周圍文字選取起來。
  • 使用 offsetWidth/offsetHeight 而非 style.width,是因為前者永遠回傳數字,不受 em、% 等單位影響。
  • 若要限制最小尺寸,在 mouseMove 裡加上 Math.max(80, ...) 這類夾擠即可。

此效果支援 Chrome、Firefox、IE、Opera 等主流瀏覽器。

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