萬盛學電腦網

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

jQuery 實作 DIV 拖曳移動核心邏輯

核心思路

利用三個滑鼠事件:

  1. mousedown:記錄滑鼠相對元素左上角的偏移量
  2. mousemove:依滑鼠位置計算元素新位置並更新
  3. mouseup:結束拖曳

CSS 定位基礎

.drag {
    position: absolute;
    background: #0000CC;
    top: 100px; left: 200px;
    padding: 0;
    cursor: move; /* 提示可拖曳 */
}

JavaScript 實作

$(document).ready(function() {
    var move = false; // 拖曳狀態旗標
    var _x, _y;       // 滑鼠相對元素左上角偏移

    $(".drag").mousedown(function(e) {
        move = true;
        _x = e.pageX - parseInt($(this).css("left"));
        _y = e.pageY - parseInt($(this).css("top"));
        $(this).css("opacity", 0.8); // 視覺回饋
    });

    $(document).mousemove(function(e) {
        if (!move) return;
        var x = e.pageX - _x;
        var y = e.pageY - _y;
        $(".drag").css({ "top": y, "left": x });
    }).mouseup(function() {
        move = false;
        $(".drag").css("opacity", 1);
    });
});

關鍵座標說明

  • e.pageX/Y:滑鼠相對文件左上角座標(含捲軸)
  • parseInt(css("left")):元素目前 left 數值
  • _x = pageX - left:滑鼠點擊點相對元素左上角的固定偏移
  • 移動時:新 left = pageX - _x,保持相對位置不變

進階擴充

  • 限制邊界:在 mousemove 中加入 Math.max(0, Math.min(maxX, x))
  • 拖曳代理:建立半透明分身跟隨滑鼠,放開時再移動真實元素
  • 觸控支援:補充 touchstart/move/end 事件
  • 使用 jQuery UI Draggable:$("#draggable").draggable(); 一行搞定
copyright © 萬盛學電腦網 all rights reserved