JS 滾動事件window.onscroll與position:fixed寫兼容IE6的回到頂部組件
現(xiàn)在網(wǎng)上的回到頂部組件,懂不懂就一大段讓人看不懂javascript代碼,還各種不兼容。起始這個組件,完全可以自己利用javascript的滾動事件window.onscroll與position:fixed手寫。IE6的兼容性問題主要出現(xiàn)在position:fixed上面,如何解決已經(jīng)在《【CSS】IE6中的position:fixed問題與隨滾動條滾動的效果》(點擊打開鏈接)介紹過了。
下面具體說說如何利用JavaScript中的滾動事件window.onscroll實現(xiàn)這個回到頂部組件。具體效果如下:
IE6:

IE8:

FireFox:

首先是HTML+CSS的布局,在頁面的最頂部布置一個id與name皆為page_top的<a></a>作為錨點,之所以要共同設(shè)置id與name一切為了兼容。
然后就是在右下角放一個position:fixed的,內(nèi)容為↑的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 id="page_top" name="page_top"></a><!--回到頂部的錨點-->
<div id="top_div"><a href="#page_top" style="text-decoration:none">↑</a></div>
<p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p>
<p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p>
<p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p>
<p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p>
<p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</p><p>占位置的內(nèi)容</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,就是用戶滾動滾動條就會觸發(fā)這個時事件,var t = document.documentElement.scrollTop || document.body.scrollTop;能夠兼容絕大部分瀏覽器,下面的t>=300是滾動條下滾300px之后,讓top_div顯示,這里用inline是以免block,會影響其它樣式。
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
相關(guān)文章
通過JS獲取Request.QueryString()參數(shù)的值實現(xiàn)方法
下面小編就為大家?guī)硪黄ㄟ^JS獲取Request.QueryString()參數(shù)的值實現(xiàn)方法。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-09-09
微信小程序?qū)崿F(xiàn)頁面導(dǎo)航的方法詳解
這篇文章主要為大家詳細介紹一下微信小程序?qū)崿F(xiàn)頁面導(dǎo)航的幾種方法以及幫助大家掌握如何使用頁面之間的導(dǎo)航跳轉(zhuǎn),感興趣的可以了解一下2022-07-07
three.js中點對象(Point)和點材質(zhì)(PointsMaterial)的具體使用
本文主要介紹了three.js中點對象(Point)和點材質(zhì)(PointsMaterial)的具體使用,文中通過示例代碼介紹的非常詳細,對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2023-07-07

