簡體   English   中英

當查看器滾動時,如何使網站的導航欄位於頂部?

[英]How do I make the navigation bar of my site stay at the top when the viewer scrolls?

我正在網站上工作,當用戶向下滾動時,我希望導航欄位於頁面頂部。 主要問題是當用戶滾動到頁面頂部時,我希望標題(顯示在導航欄上方)將導航欄向下推。 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;
}

基本上,我希望導航欄與頁面的其余部分一起向上滾動,但是當它到達頂部時,它應該停留在該位置。 有關如何在我的代碼中實現解決方案的說明將不勝感激。 謝謝。

有一個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>

希望這可以幫助

您需要將元素的offset().top與Windows當前的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);
});

小提琴的例子

請注意, scroll功能會為每個滾動的像素觸發一次,因此出於性能原因,計時器在那里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM