jquery实现头部固定导航效果

风格不统一 提交于 2020-03-31 13:15:35

 

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
    body {margin:0;padding:0;}
    .nav {width:100%;height:50px;position:fixed;top:0;left:0;background-color:#333;text-align:center;line-height:50px;}
    .nav a {margin:0 10px;color:#ddd;text-decoration:none;font-size:16px;}
    .nav .cur {font-weight:bold;color:#f90;}
    </style>
</head>
<body>
    
    <div class="nav">
        <a class="cur" href="#a1">恩恩恩</a>
        <a href="#a2">嘿嘿嘿</a>
        <a href="#a3">哈哈哈</a>
        <a href="#a4">啊啊啊</a>
    </div>
    
    <div id="a1" class="section" style="height:800px;background:#f60;"></div>
    <div id="a2" class="section" style="height:900px;background:#8cf;"></div>
    <div id="a3" class="section" style="height:1200px;background:#FC9;"></div>
    <div id="a4" class="section" style="height:800px;background:grey;"></div>
    
    
    <script src="jquery-1.11.1.min.js"></script>
    <script>
    $(function() {
        var act = $(".nav a");
        var section = $(".section");
        var timer = null;
        
        act.on("click", function() {
            var self = $(this);
            var linkHref = self.attr("href").split("#")[1];
            var target = $("#" + linkHref);
            var topPos = target.offset().top - 50;
            act.removeClass("cur");
            self.addClass("cur");
            $("html, body").animate({scrollTop: topPos}, "fast");
        });
        
        function scrollEvent() {
            var posTop = $(window).scrollTop();
            section.each(function() {
                var self = $(this);
                var elemTop = self.offset().top - 50;
                var index = 0;
                if (posTop >= elemTop) {
                    index = section.index(self);
                    act.removeClass("cur").eq(index).addClass("cur");
                }
            });
        }
        $(window).on("scroll", function() {
            //scrollEvent();
            clearTimeout(timer);
            timer = setTimeout(scrollEvent, 100);
        });
        
    });
    </script>
    
</body>
</html>

 

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!