网页前端设计

http://www.86y.org

搜索文章

js的window.onscroll事件兼容各大浏览器!

用声音读出全文关注我吧
 2016/7/8 16:54:41 阅读次数:7230

为窗口添加滚动条事件其实非常的简单,

window.onscroll=function(){};
注意在获取滚动条距离的时候
谷歌不识别document.documentElement.scrollTop,必须要加上document.body.scrollTop;即
var scrolltop=document.documentElement.scrollTop||document.body.scrollTop;
这样才能兼容各个浏览器!
 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style type="text/css">
#box{ height:50px; width:200px; background:#666; position:absolute; left:0px; top:0px;}
</style>
</head>
<body style="height:9000px;">
 
<div id="box"></div>
 
<script language="javascript">
window.onscroll = function(e){
var e =e || window.event;
var scrolltop=document.documentElement.scrollTop||document.body.scrollTop;
 
var box = document.getElementById('box');
box.style.top = scrolltop+'px'
//console.log(scrolltop); 
}
</script>
 
</body>
</html>

(完)


大家有什么问题或技术上的想法可以在此与大家分享,也可以加入前端爱好者QQ群(141999928)一起学习进步:【幸凡前端技术交流群】
如需转载请注明出处:http://www.86y.org/art_detail.aspx?id=786【js的window.onscroll事件兼容各大浏览器!】幸凡学习网
0

如果您觉得本文的内容对您的学习有所帮助,捐赠与共勉,支付宝(左)或微信(右)

阅读全文内容关闭