document.body.scrollTop的值总为零的解决办法

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

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值