scrollTop总为零原因;如何查看滚动条的位置或者说滚动条的滚动距离(待完善)

1、document.body.scrollTop的值总为零的原因
有一个功能需要判断下拉的距离,设置头部固定导航栏的颜色。

代码如下:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
body{
margin: 0;
padding: 0;
height: 1000px;
background-color: #ccc;
}
.header{
height: 100px;
width: 100%;
background-color: #E72C2C;
position: fixed;
top: 0;
}
</style>
</head>
<body>
<div>
<div id="header" class="header"></div>
</div>
<script>
window.onscroll = function () {
var sTop = document.body.scrollTop;
console.log(sTop);
if(sTop>100){
document.getElementById("header").style.backgroundColor = '#F59797';
}else{
document.getElementById("header").style.backgroundColor = '#E72C2C';
}
};
</script>
</body>
</html>
但是发现document.body.scrollTop一直是0。

查资料发现是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; 

不管有没有都可以用window.pageYoffset来获取

Safari: 

 safari 比较特别,有自己获取scrollTop的函数 : window.pageYOffset ; 

3、解决办法
因此,为了兼容所有浏览器,封装一个函数,去获取页面向上卷曲出去的距离和向左卷曲出去的距离

//获得页面向左、向上卷动的距离
function getScroll(){
return {
left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0,
top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
};
}
因此,js代码如下:

window.onscroll = function () {
//获得页面向左、向上卷动的距离
function getScroll(){
return {
left: window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft || 0,
top: window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop || 0
};
}
var sTop = getScroll().top;
console.log(sTop);
if(sTop>100){
document.getElementById("header").style.backgroundColor = '#F59797';
}else{
document.getElementById("header").style.backgroundColor = '#E72C2C';
}
};
---------------------
作者:sleepwalker_1992
来源:CSDN
原文:https://blog.csdn.net/sleepwalker_1992/article/details/80677845
版权声明:本文为博主原创文章,转载请附上博文链接!

posted @ 2018-12-30 14:07  大哥成  阅读(4065)  评论(0编辑  收藏  举报