目的:精確獲取offsetTop,解決H5滾動(dòng)監(jiān)聽的時(shí)候,獲取的offsetTop有問題,解決安卓和IOS上的表現(xiàn)不一致
先簡(jiǎn)單寫個(gè)demo,學(xué)習(xí)一下基礎(chǔ)的知識(shí)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body {
margin: 0;
padding: 0;
}
.div1 {
width: 100px;
height: 700px;
background: red;
margin-top: 50px;
padding-top: 20px;
position: relative;
}
.div2 {
width: 50px;
height: 200px;
background: blue;
margin-top: 50px;
padding-top: 20px;
position: fixed;
}
.div3 {
width: 100px;
height: 200px;
background: blue;
margin-top: 50px;
padding-top: 20px;
}
</style>
</head>
<body>
<!--
offsetParent定位父級(jí)
偏移量屬性一般就是offsetLeft、offsetTop、offsetHeight、offsetWidth這四種了,然后還有一個(gè)offsetParent屬性作為偏移的參照點(diǎn)。在網(wǎng)上看到的offsetParent的定義是:與當(dāng)前元素最近的經(jīng)過定位(position不等于static)的父級(jí)元素(感覺和絕對(duì)定位的定位點(diǎn)很類似?)。然后具體情況分為下面幾種:
1. position為fixed時(shí),offsetParent為null,offsettop的值和top相等。此時(shí)元素是以視口來定位的。
2. position非fixed,父級(jí)元素?zé)o定位(static)時(shí),offsetParent為body。
3. position非fixed,父級(jí)元素有定位時(shí),offsetParent為最近的有定位的父級(jí)元素。
4. body元素,offsetParent為null,offsettop為0(似乎是廢話)。
-->
<div id="div1" class="div1">
<div class="div2" id="div2"></div>
div1
</div>
<div class="div3" id="div3">
div3
</div>
<script>
window.addEventListener('DOMContentLoaded', function () {
var div1 = document.querySelector('#div1');
var div2 = document.querySelector('#div2');
var div3 = document.querySelector('#div3');
console.log('div1.offsetTop', div1.offsetTop, div1.offsetParent);
console.log('div2.offsetTop', div2.offsetTop, div2.offsetParent);
console.log('div3.offsetTop', div3.offsetTop, div3.offsetParent);
});
</script>
</body>
</html>
下面是大招
function getOffsetTop () {
let actualTop = element.offsetTop;
let current = element.offsetParent;
while (current !== null) {
actualTop += current.offsetTop;
current = current.offsetParent;
}
return actualTop;
}