DIV CSS 佈局教程網

方塊拖曳搭配鍵盤控制的綜合效果
編輯:JavaScript綜合知識     

這個範例把三件事組在一起:滑鼠拖曳方塊、按 Enter 讓方塊受重力落下並反彈、以及一個隨之同步位移縮放的小方塊。它示範了如何在同一元素上協調兩套輸入方式而不互相干擾。

結構

<div id="text"
     style="width:120px; height:60px; background:#F06; position:absolute;
            left:500px; top:90px; cursor:move;"></div>

拖曳邏輯

var msgObj = document.getElementById('text');
var posx = 0;
var posy = 0;
var moveable = false;
var MouseDownEvent = document.onmousedown;
var MouseMoveEvent = document.onmousemove;
var MouseUpEvent = document.onmouseup;

msgObj.onmousedown = function (evt) {
  var evt = evt || window.event;
  moveable = true;

  // 記錄滑鼠與元素左上角的偏移量
  posy = evt.clientY - parseInt(msgObj.style.top);
  posx = evt.clientX - parseInt(msgObj.style.left);

  document.onmousemove = function (evt) {
    if (moveable) {
      var evt = evt || window.event;
      msgObj.style.left = evt.clientX - posx + "px";
      msgObj.style.top  = evt.clientY - posy + "px";
    }
    change();          // 拖動時同步小方塊位置
  };

  document.onmouseup = function () {
    if (moveable) {
      // 還原原本的 handler,避免影響頁面上其他拖曳行為
      document.onmousemove = MouseMoveEvent;
      document.onmouseup = MouseUpEvent;
      moveable = false;
      posx = 0;
      posy = 0;
    }
  };
};

核心觀念是偏移量補償:按下時算出滑鼠座標與元素左上角的差值,移動時反推回去,元素才不會在抓取瞬間跳到滑鼠正下方。放開時把 document 上的 handler 還原成原本的,這是不覆蓋他人事件的禮貌做法。

鍵盤控制:重力與反彈

var v = 1;          // 速度
var a = 0.9;        // 加速度
var h = document.documentElement.clientHeight;

function scroll() {
  var timer = setInterval(function () {
    v += a;
    var top = (parseInt(msgObj.style.top) || 0);
    if (top + v > h - 70) {
      if (v < 2) clearInterval(timer);   // 反彈衰減到極小就停止
      msgObj.style.top = h - 70 + "px";
      v = -v * 0.5;                       // 反向並衰減,模擬能量損失
    } else {
      msgObj.style.top = top + v + "px";
    }
    change();
  }, 10);
}

$(document).keyup(function (e) {
  var e = e || window.event;
  if (e.which == 13) {      // Enter 鍵
    scroll();
  }
});

這是一段簡易的物理模擬:v 每帧加重力加速度 a,碰到底部時把速度取負並乘 0.5 模擬碰撞損耗,反覆幾次後速度小於 2 就停止。用 10 毫秒的間隔換取較細緻的落下過程。

同步縮放的小方塊

var x = 4;
var y = 4;

function newpro() {
  var Height = document.documentElement.clientHeight;
  var Width = document.documentElement.clientWidth;
  var newobj = document.createElement('div');
  newobj.setAttribute('id', 'bigbox');
  newobj.style.position = 'absolute';
  newobj.style.left = 20 + "px";
  newobj.style.top = 80 + "px";
  newobj.style.height = Height / x + "px";
  newobj.style.width = Width / y + "px";
  newobj.style.borderWidth = 1 + "px";
  newobj.style.borderColor = "#ff6500";
  newobj.style.borderStyle = 'solid';
  newobj.innerHTML = '<div id="minbox"></div>';
  document.body.appendChild(newobj);
  change();
}

function change() {
  var minobj = document.getElementById('minbox');
  minobj.style.position = 'absolute';
  minobj.style.left = parseInt(msgObj.style.left) / x + "px";
  minobj.style.top = parseInt(msgObj.style.top) / y + "px";
  minobj.style.height = 20 + "px";
  minobj.style.width = 30 + "px";
  minobj.style.background = "#F06";
}

window.onload = function () {
  newpro();
};

bigbox 是視窗尺寸的四分之一(寬除以 4、高除以 4),minbox 則是 msgObj 座標除以同樣的比例。兩者形成一個縮小的「全局態勢圖」,拖曳或落下時呼叫 change() 即同步更新,這是小地圖(minimap)最基礎的實作。

值得改進的地方

事件模型

直接用 document.onmousemove = ... 會覆蓋頁面上其他程式的同名 handler。應改用 addEventListener,並在 mouseup 時 removeEventListener,才不會互相干擾。

缺少邊界限制

拖曳沒有做上下左右的夾擠,方塊可以被拖出視窗外再也拉不回來。應在計算新座標時加上 Math.max(0, Math.min(x, maxWidth)) 限制。

用 pointer 事件取代 mouse 事件

Pointer Events 統一了滑鼠、觸控與手寫筆,並提供 setPointerCapture,指標移出元素後拖曳仍不中斷:

el.addEventListener('pointerdown', function (e) {
  this.setPointerCapture(e.pointerId);
  // ... 後續處理
});

動畫效能

10 毫秒一次的 setInterval 改 left/top 會持續觸發重排。改用 requestAnimationFrame 搭配 transform,能與螢幕刷新同步且不觸發 layout:

function tick() {
  v += a;
  el.style.transform = 'translateY(' + top + 'px)';
  if (needMore) requestAnimationFrame(tick);
}

最後,鍵盤控制目前只綁了 Enter,若作為正式功能,方向鍵移動會更符合使用者預期;同時應避免 e.which(已廢棄),改用 e.key === 'Enter'。

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