js兼容写法为document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop

<!DOCTYPE html>
<html>
<head>
	<title>js兼容写法为var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;</title>
	<meta charset="utf-8">
	<script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>   
</head>
<body>
<div style="width: 2000px;height: 3000px;background-color: #ccc;"></div>
<p id="demo"></p>
<input style="position: fixed;top: 100px;right: 100px;width: 60px;height: 20px;background-color: #666; line-height: 20px;text-align: center;" />
<script>
var ip = document.getElementsByTagName("input")[0];
ip.onclick = function(){
	alert($(window).scrollTop()); //是网页被卷去的高度
	alert(document.documentElement.scrollTop); //是网页被卷去的高度,具有DTD的情况下可以取的高度,否则为0
	alert(document.body.scrollTop); //是网页被卷去的高度,具有DTD的情况下取不到的高度0,在没有DTD的状况下取得高度
	//兼容写法为var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
	alert(document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop);
}
ip.οnkeydοwn= function(){
	//兼容写法为var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
	alert(document.documentElement.scrollTop);
	alert(window.pageYOffset); //safari 比较特别,有自己获取scrollTop的函数 : window.pageYOffset ;
	alert(document.body.scrollTop);
	alert(document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop);
}

ip.onmouseover = function() {
    window.scrollBy(100, 100);//每次滚动100,100

    if (window.pageXOffset !== undefined) {  // 所有浏览器,除了 IE9 及更早版本
        alert("水平滚动: " + window.pageXOffset 
        + ", 垂直滚动: " + window.pageYOffset);
    } else {   // IE9 及更早版本
        alert("水平滚动: " + document.documentElement.scrollLeft 
        + ", 垂直滚动: " + document.documentElement.scrollTop);
    }
}
alert(  0 || undefined ); // undefined
//  0 || undefined>>>undefined
//  10 || undefined>>>10
alert(  undefined || 0 ); // 0
//  undefined || 0 >>>0
alert(  undefined || 10 ); // 10
//  undefined || 10 >>>10
</script>

</body>
</html> 

所有主流浏览器都支持 pageXOffset 和 pageYOffset 属性。IE 8 及 更早 IE 版本不支持该属性,但可以使用 document.documentElement.scrollLeft 和 document.documentElement.scrollTop 属性 。


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值