在頁面中根據使用者輸入,將游標區塊移動到指定元素(A、B、C 區塊)的位置。展示如何使用 getBoundingClientRect() 取得元素相對視窗的座標。
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>JavaScript 元素定位範例</title>
<style>
div#a { width: 500px; }
div { border: 1px solid #000; padding: 10px; }
#cursor {
position: absolute;
background-color: #ff0;
width: 20px;
height: 20px;
left: 50px;
top: 300px;
}
</style>
<script>
// 取得元素相對視窗左上角座標
function positionObject(obj) {
var rect = obj.getBoundingClientRect();
return [rect.left, rect.top];
}
window.onload = function() {
// 測試 documentElement 座標
var tst = document.documentElement.getBoundingClientRect();
alert("documentElement top: " + tst.top);
var cont = 'A';
var cursor = document.getElementById("cursor");
while (cont) {
cont = prompt("想移動游標到哪個區塊?", "A");
if (cont) {
cont = cont.toLowerCase();
if (cont === "a" || cont === "b" || cont === "c") {
var elem = document.getElementById(cont);
var pos = positionObject(elem);
console.log("元素座標:", pos);
// 更新游標位置
cursor.setAttribute("style",
"top:" + pos[1] + "px; left:" + pos[0] + "px");
}
}
}
};
</script>
</head>
<body>
<div id="a">
<p>A</p>
<div id="b">
<p>B</p>
<div id="c">
<p>C</p>
</div>
</div>
</div>
<div id="cursor"></div>
</body>
</html>
getBoundingClientRect()回傳一個 DOMRect 物件,包含以下唯讀屬性:
left、top:元素左上角相對視窗座標right、bottom:元素右下角相對視窗座標width、height:元素尺寸(含 padding、border)x、y:等同 left/top(較新規格)頁面滾動時座標會改變。若需文件座標,需加上 window.scrollX/scrollY:
function getDocumentPosition(elem) {
var rect = elem.getBoundingClientRect();
return {
left: rect.left + window.scrollX,
top: rect.top + window.scrollY
};
}
width/height 包含 padding + border,不包含 margin。
巢狀結構中,父元素的 getBoundingClientRect() 範圍包含所有子元素與文字節點。
CSS transform 會影響回傳座標,回傳的是變換後的幾何位置。
IntersectionObserver 更佳)對於「元素是否在可視區」判斷,推薦使用 IntersectionObserver API,效能更好、API 更語意化:
var observer = new IntersectionObserver(function(entries) {
entries.forEach(function(entry) {
if (entry.isIntersecting) {
console.log("元素進入可視區");
}
});
});
observer.observe(document.getElementById("target"));