1. 在模拟点击返回顶部按钮,页面就会滑动到顶部,但是在获取页面卷去头部的大小时,document.body.scrollTop总是为0. 后面尝试用了document.documentElement.scrollTop就可以获得被卷去的头部。
<!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>
header{
height: 400px;
background-color: pink;
}
nav{
height: 400px;
background-color: red;
}
.main{
height: 800px;
background-color: green;
}
.fix{
position: fixed;
bottom: 20px;
right: 20px;
cursor: pointer;
}
</style>
</head>
<body>
<header>
aaaa
</header>
<nav>
aaa
</nav>
<div class="main">
</div>
<div class="fix">
top
</div>
<script>
var that;
class GoBack{
constructor(id){
that = this;
this.topBtn = document.querySelector('.fix');
this.init();
}
init(){
this.topBtn.onclick = this.goback;
console.log(document.body.scrollTop);
console.log(document.documentElement.scrollTop);
}
goback(){
document.documentElement.scrollTop = 0;
}
}
var goback = new GoBack('.fix');
</script>
</body>
</html>
后来查了下资料,是DTD 的问题:
页面指定了DTD,即指定了DOCTYPE时,使用document.documentElement.scrollTop。
页面没有DTD,即没指定DOCTYPE时,使用document.body.scrollTop。
2、各浏览器下 scrollTop的差异
IE:
对于没有doctype声明的页面,使用 document.body.scrollTop 或 document.documentElement.scrollTop;
对于有doctype声明的页面,则使用 document.documentElement.scrollTop;
Chrome、Firefox:
对于没有doctype声明的页面,使用 document.body.scrollTop 来获取 scrollTop高度 ;
对于有doctype声明的页面,则使用 document.documentElement.scrollTop;
Safari:
safari 比较特别,有自己获取scrollTop的函数 : window.pageYOffset ;
3、解决办法
因此,为了兼容所有浏览器,封装一个函数,去获取页面向上卷曲出去的距离和向左卷曲出去的距离
left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0,
top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0