萬盛學電腦網

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

JavaScript 實現鼠標拖動框選功能完整教程

效果描述

  • 按下鼠標左鍵不放,拖動生成選取框
  • 框選區域內的元素高亮/選中
  • 支持點擊空白處取消選中
  • 兼容主流瀏覽器

核心實現邏輯

  1. mousedown:記錄起始座標,創建選取框 DIV,綁定 mousemove/mouseup
  2. mousemove:計算當前寬高,更新選取框尺寸/位置,碰撞檢測選中元素
  3. mouseup:清理事件,隱藏選取框,觸發選中回調

完整代碼實現

<style>
.fileDiv {
    float: left; width: 100px; height: 100px;
    text-align: center; line-height: 100px; font-size: 12px;
    border: 1px solid #ccc; margin: 10px; cursor: default;
    user-select: none; /* 禁用文字選取干擾 */
}
.seled { border: 2px solid #f00; background: #D6DFF7; }
#selectBox {
    position: absolute; border: 1px dashed #00f; background: rgba(0,0,255,0.1);
    display: none; pointer-events: none; z-index: 999;
}
</style>

<div id="container">
    <div class="fileDiv">文件 1</div>
    <div class="fileDiv">文件 2</div>
    <div class="fileDiv">文件 3</div>
    <div class="fileDiv">文件 4</div>
    <div class="fileDiv">文件 5</div>
    <div class="fileDiv">文件 6</div>
</div>
<div id="selectBox"></div>

<script>
// 工具函數
function $(id) { return document.getElementById(id); }
function $$(selector, ctx) { return (ctx || document).querySelectorAll(selector); }

// 獲取元素絕對位置
function getOffset(el) {
    var rect = el.getBoundingClientRect();
    return { left: rect.left + window.scrollX, top: rect.top + window.scrollY };
}

// 碰撞檢測:選取框與元素是否相交
function intersect(box, el) {
    var elRect = el.getBoundingClientRect();
    return !(box.right < elRect.left || box.left > elRect.right ||
             box.bottom < elRect.top || box.top > elRect.bottom);
}

var selectBox = $('selectBox');
var container = $('container');
var items = $$('.fileDiv', container);
var startX, startY, selecting = false;

container.onmousedown = function(e) {
    e = e || window.event;
    // 忽略右鍵、點擊在子元素上(由冒泡觸發)
    if (e.button !== 0 || e.target !== container) return;

    selecting = true;
    startX = e.clientX;
    startY = e.clientY;

    selectBox.style.left = startX + 'px';
    selectBox.style.top = startY + 'px';
    selectBox.style.width = '0';
    selectBox.style.height = '0';
    selectBox.style.display = 'block';

    document.onmousemove = function(e) {
        if (!selecting) return;
        e = e || window.event;

        var curX = e.clientX, curY = e.clientY;
        var left = Math.min(startX, curX);
        var top = Math.min(startY, curY);
        var width = Math.abs(curX - startX);
        var height = Math.abs(curY - startY);

        selectBox.style.left = left + 'px';
        selectBox.style.top = top + 'px';
        selectBox.style.width = width + 'px';
        selectBox.style.height = height + 'px';

        // 碰撞檢測並切換選中樣式
        var boxRect = {
            left: left, top: top,
            right: left + width, bottom: top + height
        };
        for (var i = 0; i < items.length; i++) {
            var el = items[i];
            if (intersect(boxRect, el)) {
                el.classList.add('seled');
            } else {
                el.classList.remove('seled');
            }
        }
    };

    document.onmouseup = function() {
        selecting = false;
        selectBox.style.display = 'none';
        document.onmousemove = document.onmouseup = null;

        // 收集選中項
        var selected = [];
        for (var i = 0; i < items.length; i++) {
            if (items[i].classList.contains('seled')) {
                selected.push(items[i].textContent);
            }
        }
        console.log('選中:', selected);
        // 觸發自定義事件或回調
    };

    // 防止默認拖拽行為(如圖片拖拽)
    e.preventDefault();
};

// 點擊空白取消選中
container.onclick = function(e) {
    if (e.target === container) {
        for (var i = 0; i < items.length; i++) {
            items[i].classList.remove('seled');
        }
    }
};
</script>

關鍵技術點詳解

1. 座標系統統一

  • 使用 clientX/clientY (視口座標) 配合 getBoundingClientRect(),避免滾動偏移計算
  • 選取框 position:absolute 相對 body 定位,直接使用視口座標

2. 碰撞檢測算法 (AABB)


// 軸對齊包圍盒相交判斷
function intersect(rect1, rect2) {
    return !(rect1.right < rect2.left || rect1.left > rect2.right ||
             rect1.bottom < rect2.top || rect1.top > rect2.bottom);
}

O(1) 時間複雜度,適合百元素級別。大量元素可用空間索引 (QuadTree/Grid)。

3. 事件綁定策略

  • mousedown 綁在容器上(事件委派)
  • mousemove/mouseup 綁在 document 上,確保鼠標移出容器仍能追蹤
  • 結束時及時解綁,防止內存洩漏

4. 防止干擾

  • user-select: none 禁用文字選取
  • pointer-events: none 讓選取框不阻擋鼠標事件
  • e.preventDefault() 禁用瀏覽器默認拖拽(圖片/鏈接)

進階擴展

  1. Shift/Ctrl 多選修飾鍵:在 mousedown 判斷 e.shiftKey/e.ctrlKey 決定是否清空原選中
  2. 滾動容器自動滾動:mousemove 時檢測邊緣,調用 container.scrollLeft/Top
  3. 觸屏支援:添加 touchstart/move/end 事件並行處理
  4. 選取框磁吸對齊:移動時吸附到最近元素邊緣
  5. 框選完成後上下文菜單:contextmenu 事件顯示操作選單

現代框架封裝思路


// Vue 3 Composition API 封裝範例
export function useSelection(containerRef, itemSelector) {
    const selected = ref([]);
    const selectBox = ref({ show: false, x: 0, y: 0, w: 0, h: 0 });

    // ... 核心邏輯同原生版,使用 ref/reactive 響應式數據
    // 暴露 selected、startSelection、clearSelection 等

    return { selected, selectBox, clearSelection };
}

結語

鼠標框選是「選中容器 → 記錄起點 → 移動繪框 → 碰撞檢測 → 鬆開確認」的標準流程。核心難點在於座標系統統一、高效碰撞檢測、事件生命周期管理。理解原生實現後,在 Vue/React 中封裝為可復用 Hook/組件即可輕鬆應用於文件管理、圖形編輯器、數據表格等場景。

copyright © 萬盛學電腦網 all rights reserved