Navigation bar fixed top

1.

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>js scroll to the specified position navigation bar fixed top</title>
        <style type="text/css">
             body{height: 2500px; margin: 0; padding: 0;}
            .banner{height: 250px; width: 100%; background: #e5e5e5;}
            .bignav{width: 100%; background: #000;}
            .nav{ background:#000; width: 1200px; margin: 0 auto; height: 45px;}
            .nav a{display: block; width: 200px;float: left; color: #fff; text-decoration: none; text-align: center; line-height: 45px;}
        </style>
    </head>
    <body>
        <div class="banner">
            
        </div>
        <div class="bignav" id="bignav">
            <div class="nav">
                <a href="#">首页</a>
                <a href="#">首页</a>
                <a href="#">首页</a>
                <a href="#">首页</a>
                <a href="#">首页</a>
                <a href="#">首页</a>
            </div>
        </div>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        <p>Other content</p>
        
        <script type="text/javascript">
            window.onscroll=function(){
                var topScroll =document.body.scrollTop;//Scroll distance, distance from the top
                var bignav = document.getElementById("bignav");//Get the navigation bar id
                if(topScroll > 250){ //Execute the following when the scroll distance is greater than 250px
                    bignav.style.position = 'fixed';
                    bignav.style.top = '0';
                    bignav.style.zIndex = '9999';
                }else{//When the scroll distance is less than 250, execute the following content, which is to restore the navigation bar to its original state
                    bignav.style.position = 'static';
                }
            }
        </script>
    </body>
</html>

 

 

 

2.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326469097&siteId=291194637