js網頁滾動條滾動事件


在做js返回頂部的效果時,要監聽網頁滾動條滾動事件,這個事件就是:window.onscroll。當onscroll事件發生時,用js獲得頁面的scrollTop值,判斷scrollTop為一個設定值時,顯示“返回面部”
js網頁滾動條滾動事件

<style type="text/css">
#top_div{
    position:fixed;
    bottom:80px;
    right:0;
    display:none;
}
</style>
<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>
<a name="top">頂部<a>
<div id="top_div"><a href="#top">返回頂部</a></div>
<br />
<br />
<div>
這里盡量多些<br />以便頁面出現滾動條,限於篇幅本文此處略去
</div>

例子語法解釋
在 style 標簽中首先定義 top_div css 屬性:position:fixed;display:none; 是關鍵
javascript 語句中,t 得到滾動條向下滾動的位置,|| 是為了更好兼容性考慮
當滾動超過 300 (像素)時,將 top_div css display 屬性設置為顯示(inline),反之則隱藏(none)
必須設定 DOCTYPE 類型,在 IE 中才能利用 document.documentElement 來取得窗口的寬度及高度

 

轉自:http://www.altmi.com/zg/index.php/archives/67/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM