scroll家族

scroll家族属性

document.body.scrollWidth:网页正文全文宽
document.body.scrollHeight:网页正文全文高
document.body.scrollTop:网页正文被移去的高(滚动高度)
document.body.scrollLeft:网页正文被移去的左(滚动宽度)
但在实际开发中使用较多的是scrollTop

scroll兼容性问题

首先要提到一个概念是严格模式和怪异模式
如果你不清楚可参考:
严格模式和怪异模式

CSS样式

<style>
    body {
        height: 2000px;
    }
</style>

怪异模式下的兼容

<script>
    window.onscroll = function() {
        
        //怪异模式  低版本IE中使用
       console.log(document.body.scrollTop);
    }
</script>

严格模式下的兼容

使用document.documentElement.scrollTop ,这里以谷歌为例

<script>
    window.onscroll = function() {
        
        //严格模式做兼容
        console.log(document.documentElement.scrollTop);    //兼容
    }
</script>

所有版本兼容

<script>
    window.onscroll = function() { 
        //所有版本都兼容
        console.log(document.documentElement.scrollTop || document.body.scrollTop);
   
    }
</script>

高版本浏览器兼容

使用window.pageYOffset,是目前最常见的写法之一

<script>
    window.onscroll = function() {

        console.log(window.pageYOffset);     //高版本浏览器
    }
</script>

兼容综合写法

<script>
    window.onscroll = function() {
        var scroll = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
		console.log(scroll);
    }
</script>

示例图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值