【javascript】菜單滾動至頂部后固定


現在很多網站都有這樣的一個效果,當頁面滾動到一定高度時,菜單欄會固定在頁面頂部。其實就是改變 position 的值。

html 代碼:

<!DOCTYPE HTML>
<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" type="text/css" href="css/base.css" media="all"/>
    <style type="text/css">
    .wrapper{width:1000px;height:2000px;margin-left:auto;margin-right:auto;}
    .header{height:150px;}
    #nav{padding:10px;position:relative;top:0;background:black;width:1000px;}
    a{display:inline-block;margin:0 10px;*display:inline;zoom:1;color:white;}
    </style>
</head>
<body>
    <div class="wrapper">
        <div class="header"></div>
        <div id="nav">
            <a href="#">11111</a>
            <a href="#">22222</a>
            <a href="#">33333</a>
            <a href="#">44444</a>
            <a href="#">55555</a>
        </div>
    </div>
</body>
</html>
<script type="text/javascript" src="menuFixed.js"></script>
<script type="text/javascript">
window.onload = function(){
    menuFixed('nav');
}
</script>

menuFixed.js 代碼:

function menuFixed(id){
    var obj = document.getElementById(id);
    var _getHeight = obj.offsetTop;
    
    window.onscroll = function(){
        changePos(id,_getHeight);
    }
}
function changePos(id,height){
    var obj = document.getElementById(id);
    var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
    if(scrollTop < height){
        obj.style.position = 'relative';
    }else{
        obj.style.position = 'fixed';
    }
}

最后需要說明的是,該效果在 ie6 下不支持,因為 ie6 不支持 position:fixed;


免責聲明!

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



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