美文网首页
js-滚动到指定位置导航栏固定顶部

js-滚动到指定位置导航栏固定顶部

作者: 捔落纏綿 | 来源:发表于2018-06-28 16:24 被阅读0次

    <!doctype html>
    <html>
    <head>
    <meta charset="utf-8">
    <title>无标题文档</title>
    <link rel="stylesheet" type="text/css" href="css/index.css">
    </head>

    <body>
    <div class="banner"></div>
    <nav id="nav"></nav>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    <p>其他内容</p>
    </body>
    </html>

    <script type="text/javascript">
    window.onscroll=function(){
    var topScroll =window.pageYOffset;//滚动的距离,距离顶部的距离
    //alert(topScroll);
    var bignav = document.getElementById("nav");//获取到导航栏id
    if(topScroll > 500){ //当滚动距离大于250px时执行下面的东西
    bignav.style.position = 'fixed';
    bignav.style.top = '0';
    bignav.style.zIndex = '9999';
    }else{//当滚动距离小于250的时候执行下面的内容,也就是让导航栏恢复原状
    bignav.style.position = 'static';
    }
    }
    </script>

    相关文章

      网友评论

          本文标题:js-滚动到指定位置导航栏固定顶部

          本文链接:https://www.haomeiwen.com/subject/gxtnyftx.html