jQuery学习 (固定导航栏效果)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>固定导航栏</title>
    <style type="text/css">
        * {
            margin: 0;
            padding: 0;
        }

        .main {
            width: 1000px;
            margin: 0 auto;
        }
        /*.top {
            height: 171px;
        }
        .nav {
            height: 86px;
        }*/
    </style>
    <script src="jquery-1.12.2.js"></script>
    <script>
        $(function () {
            $(window).scroll(function () {
                //获取页面卷曲出去的高度和.top的div的高度对比
                if($(document).scrollTop()>$(".top").height()){
                    $(".nav").css({"position":"fixed","top":0});
                    $(".main").css("marginTop",$(".nav").height());
                }else{
                    $(".nav").css("position","static");
                    $(".main").css("marginTop",0);
                }
            });
        });

    </script>
</head>

<body>
<div class="top">
    <img src="images/top.png" />
</div>
<div class="nav">
    <img src="images/nav.png" />
</div>
<div class="main">
    <img src="images/main.png" />
</div>
</body>

</html>

相关推荐