萬盛學電腦網

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

JavaScript 判斷滑鼠是否在 DIV 區域內的三種方法比較 JavaScript 判斷滑鼠是否在 DIV 區域內的三種方法比較

方法一:事件驅動(mouseover / mouseout / mouseleave)

最直觀,但必須發生事件才能知曉狀態。


var div = document.getElementById('div_1');
div.onmouseover = function() {
    this.innerText = "滑鼠移入!";
    this.style.fontWeight = "normal";
};
div.onmouseout = function() {
    this.innerText = "滑鼠移出!";
    this.style.fontWeight = "bold";
    this.style.color = "red";
};

<div id="div_1" style="background:lightblue; width:400px; height:300px;"
     onmouseover="chkIn()" onmouseout="chkOut()">This is a DIV</div>

缺點:無法在「非事件觸發時」主動查詢當前狀態。

方法二:座標碰撞檢測(通用、可主動輪詢)

取得滑鼠 clientX/Y,遍歷頁面元素判斷是否包含該座標。


function checkIn(e) {
    e = e || window.event;
    var x = e.clientX, y = e.clientY;
    var msgs = [];
    for (var i = 0; i < document.body.children.length; i++) {
        var el = document.body.children[i];
        if (x > el.offsetLeft &&
            x < el.offsetLeft + el.clientWidth &&
            y > el.offsetTop &&
            y < el.offsetTop + el.clientHeight) {
            msgs.push("滑鼠在層 " + el.id + " 範圍內");
        } else {
            msgs.push("滑鼠在層 " + el.id + " 範圍外");
        }
    }
    alert(msgs.join("\n"));
}
document.onclick = checkIn; // 點擊時檢測

注意:offsetLeft/Top 為相對 offsetParent,巢狀結構需累加或用 getBoundingClientRect() 更準確。

方法三:contains() 判斷事件目標(最簡單實用)


div.onmouseover = function(e) {
    e = e || window.event;
    var target = e.target || e.srcElement;
    if (this.contains(target)) {
        console.log("滑鼠進入 div 內部元素:" + target.tagName);
    }
};

Node.contains(otherNode) 回傳布林值,表示 otherNode 是否為該節點的後代(含自身)。IE9+、所有現代瀏覽器支援。

進階:即時追蹤滑鼠座標(不依賴事件觸發元素)


document.addEventListener('mousemove', function(e) {
    var x = e.clientX, y = e.clientY;
    var el = document.elementFromPoint(x, y); // 取得該座標最上層元素
    // 判斷 el 是否為目標 div 或其後代
    var targetDiv = document.getElementById('myDiv');
    if (targetDiv.contains(el)) {
        // 在區域內
    } else {
        // 在區域外
    }
});

document.elementFromPoint(x, y) 直接回傳視窗座標下的最上層元素,配合 contains() 判斷極為高效。

選型建議

場景推薦方法理由
僅需進入/離開觸發 UI 變化mouseenter/mouseleave (或 hover)原生事件、無輪詢、效能最好
需在任意時刻主動檢查elementFromPoint + contains即時、準確、無需遍歷所有元素
需檢查多個區域、碰撞偵測getBoundingClientRect + 座標比對適合遊戲/拖曳邏輯
舊 IE 相容(IE8-)contains() 或 offset 累加elementFromPoint 不支援
copyright © 萬盛學電腦網 all rights reserved