最直觀,但必須發生事件才能知曉狀態。
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() 更準確。
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 不支援 |