【问题标题】:How do I make the navigation bar of my site stay at the top when the viewer scrolls?当查看器滚动时,如何使我的网站的导航栏保持在顶部?
【发布时间】:2013-11-16 14:38:47
【问题描述】:

我正在开发我的网站,我希望在用户向下滚动时让导航栏保持在页面顶部。主要问题是当用户滚动到页面顶部时,我希望标题(出现在导航栏上方)向下推动导航栏。 HTML 如下所示:

//this is the header (should scroll)
<p1 id="a"><a href="index.html" id="linkNoStyle">TITLE</a></p1>
<p1 id="b">SUBTITLE</p1>

//this div is the nav bar (should stay at top)
<div id="div">
    <a href="projects.html" id="link">PROJECTS</a>
    &nbsp;
    &nbsp;
    <a href="ideas.html" id="link">IDEAS</a>
    &nbsp;
    &nbsp;
    <a href="contact.html" id="link">CONTACT</a>
</div>

//this is also part of the nav bar (should stay at top)
<hr size="5" color=black>

CSS 看起来像这样:

#a{
    font-family:Futura;
    font-size:80pt;
    color:black;
}

#b{
    font-family:Futura;
    color:grey;
}

#div{
    padding-top:3px;
    padding-left:10px;
    font-family:Futura;
    background-color:#ff6600;
    color:white;
    height:25px;
}

基本上,我希望导航栏与页面的其余部分一起向上滚动,但是当它到达顶部时,它应该停留在那里。将不胜感激有关如何在我的代码中实施解决方案的说明。谢谢。

【问题讨论】:

  • 提示:position: fixed;$(window).scroll(...)

标签: javascript jquery html css navbar


【解决方案1】:

有一个 jQuery 插件可以为您完成。它被称为sticky。官网在这里:http://stickyjs.com/

这里的代码:

<script src="jquery.js"></script>
<script src="jquery.sticky.js"></script>
<script>
    $(document).ready(function(){
        $("#sticker").sticky({topSpacing:0});
    });
</script>

希望对你有帮助

【讨论】:

    【解决方案2】:

    您需要将元素的offset().top 与窗口当前的scrollTop 进行比较。试试这个:

    var timer;
    $(window).scroll(function() {
        var $div = $('#div');
        clearTimeout(timer);
        timer = setTimeout(function() {
            if ($div.offset().top < $(this).scrollTop()) {
                $div.addClass('fixed');
            }
            else {
                $div.removeClass('fixed');
            }
        }, 250);
    });
    

    Example fiddle

    请注意,scroll 函数每滚动一个像素就会触发一次,因此出于性能原因,计时器在那里。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多