JS 滚动事件window.onscroll与position:fixed写兼容IE6的

现在网上的回到顶部组件,懂不懂就一大段让人看不懂javascript代码,还各种不兼容。起始这个组件,完全可以自己利用javascript的滚动事件window.onscroll与position:fixed手写。IE6的兼容性问题主要出现在position:fixed上面,如何解决已经在《【CSS】IE6中的position:fixed问题与随滚动条滚动的效果》(点击打开链接)介绍过了。

下面具体说说如何利用JavaScript中的滚动事件window.onscroll实现这个回到顶部组件。具体效果如下:

IE6:

JS 滚动事件window.onscroll与position:fixed写兼容IE6的


IE8:

JS 滚动事件window.onscroll与position:fixed写兼容IE6的


FireFox:

JS 滚动事件window.onscroll与position:fixed写兼容IE6的


首先是HTML+CSS的布局,在页面的最顶部布置一个id与name皆为page_top的<a></a>作为锚点,之所以要共同设置id与name一切为了兼容。

然后就是在右下角放一个position:fixed的,内容为↑的div,当然你想搞得炫一点可以弄成一张图片,甚至搞成♂也可以,这个div一开始是隐藏的。

最后是一大堆没有意义的、占位置的<p>,没什么好说的。

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>回到顶部</title> <style type="text/css"> #top_div{ position:fixed; bottom:0px; right:0px; display:none; /*兼容IE6的position:fixed*/ _position: absolute; _top: expression(eval( document.documentElement.scrollTop + document.documentElement.clientHeight-this.offsetHeight- (parseInt(this.currentStyle.marginTop,10)||0)- (parseInt(this.currentStyle.marginBottom,10)||0))); _margin-bottom:0px; _margin_right:0px; } </style> </head> <body> <a></a><!--回到顶部的锚点--> <div><a href="#page_top">↑</a></div> <p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p> <p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p> <p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p> <p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p> <p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p><p>占位置的内容</p> </body> </html>

之后的脚本部分,一切很明朗了:

<script type="text/javascript"> window.onscroll = function(){ var t = document.documentElement.scrollTop || document.body.scrollTop; var top_div = document.getElementById("top_div"); if (t >= 300) { top_div.style.display = "inline"; } else { top_div.style.display = "none"; } } </script>

仅有一个滚动事件window.onscroll,就是用户滚动滚动条就会触发这个时事件,var t = document.documentElement.scrollTop || document.body.scrollTop;能够兼容绝大部分浏览器,下面的t>=300是滚动条下滚300px之后,让top_div显示,这里用inline是以免block,会影响其它样式。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wzdpdf.html