萬盛學電腦網

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

jQuery 實現 Div 拖曳與鍵盤控制綜合範例

綜合展示:滑鼠拖曳 <div> 移動、按 Enter 鍵觸發重力下落彈跳動畫、自動生成縮圖預覽區同步顯示位置。包含事件綁定、座標計算、動畫迴圈、動態建立元素等實用技巧。

核心功能模組

  1. 拖曳移動:mousedown 記錄初始偏移 → mousemove 更新 left/top → mouseup 釋放。
  2. 鍵盤觸發重力動畫:按 Enter (e.which==13) 啟動 setInterval,模擬重力加速度 v+=a,觸底反彈衰減 v=-v*0.5,直到靜止。
  3. 縮圖同步:建立縮小版容器 #bigbox 內的 #minbox,根據主物件座標按比例縮放顯示位置。

關鍵代碼片段

var msgObj = document.getElementById('text');
var posx = 0, posy = 0, moveable = false;

msgObj.onmousedown = function(evt) {
    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) {
            evt = evt || window.event;
            msgObj.style.left = evt.clientX - posx + "px";
            msgObj.style.top = evt.clientY - posy + "px";
        }
        change(); // 更新縮圖
    };
    document.onmouseup = function() {
        if (moveable) {
            document.onmousemove = document.onmouseup = null;
            moveable = false; posx = posy = 0;
        }
    };
};

var v = 1, a = 0.9, 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) { if (e.which == 13) scroll(); });

function newpro() { // 建立縮圖區
    var H = document.documentElement.clientHeight, W = document.documentElement.clientWidth;
    var x = 4, y = 4;
    var newobj = document.createElement('div');
    newobj.id = 'bigbox';
    newobj.style.cssText = 'position:absolute;left:20px;top:80px;border:1px solid #ff6500;';
    newobj.style.height = H/x + 'px'; newobj.style.width = W/y + 'px';
    newobj.innerHTML = '<div id="minbox"></div>';
    document.body.appendChild(newobj);
    change();
}
function change() {
    var minobj = document.getElementById('minbox');
    minobj.style.cssText = 'position:absolute;background:#F06;height:20px;width:30px;';
    minobj.style.left = parseInt(msgObj.style.left)/x + 'px';
    minobj.style.top = parseInt(msgObj.style.top)/y + 'px';
}
window.onload = newpro;

改良建議

  • 使用 addEventListener 替代直接指派 onmousemove,避免覆蓋其他監聽器。
  • 拖曳時建議加上 user-select: none 防止文字被選取。
  • 重力動畫改用 requestAnimationFrame 更流暢。
  • 現代拖曳可直接使用 HTML5 Drag and Drop API 或 pointer events 統一處理滑鼠/觸控。
copyright © 萬盛學電腦網 all rights reserved