元素的位置屬性一直是很容易弄混淆的地方,各種高度寬度距離,每次使用的時(shí)候都需要各種查查查。今天就將相關(guān)屬性做一個(gè)歸類(lèi)整理,通過(guò)畫(huà)圖以最直觀的方式展現(xiàn),也方便日后查閱。
client 相關(guān)屬性
-
clientWidth/clientHeight
表示一個(gè)元素的可視區(qū)域的寬高,包含元素內(nèi)容以及內(nèi)邊距,不包含滾動(dòng)部分。
client.png
offset 相關(guān)屬性
-
offsetWidth/offsetHeight
表示一個(gè)元素的標(biāo)準(zhǔn)寬高,它包含了邊框、內(nèi)邊距、元素內(nèi)容以及滾動(dòng)條。
offset.png
-
offsetLeft/offsetTop
表示當(dāng)前元素頂部/左邊距離最近父元素頂部/左邊的距離。
scrolltop.png
scroll 相關(guān)屬性
-
scrollWidth/scrollHeight
表示一個(gè)元素內(nèi)容區(qū)域的實(shí)際大小,包括不在頁(yè)面中的可滾動(dòng)部分(內(nèi)容和內(nèi)邊距)。
scroll.png
-
scrollTop/scrollBottom
表示在有滾動(dòng)條的時(shí),元素可視區(qū)域頂部距離元素頂部的距離,也就是已經(jīng)滾動(dòng)了多少距離。
scrolltop.png
拓展應(yīng)用 - 滾動(dòng)加載
示例:
scrollMore.png
代碼:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>滾動(dòng)加載</title>
<style> .parent {
width: 300px;
height: 200px;
margin: 100px auto;
border: 1px solid #ccc;
overflow-y: scroll;
word-break: break-all;
}</style>
</head>
<body>
<div class="parent" id="target">
<div class="child">
gagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagdsagdagadgcontentgagdaggdgdsagds
</div>
</div>
<script> let target = document.getElementById("target");
target.addEventListener("scroll", function () {
const clientHeight = target.clientHeight;
const scrollTop = target.scrollTop;
const scrollHeight = target.scrollHeight;
if (clientHeight + scrollTop >= scrollHeight) {
// 到底部了
console.log("到底部了");
}
});</script>
</body>
</html>