簡體   English   中英

Ghost dom元素導航欄固定頂部不會保持原位

[英]Ghost dom element navbar fixed top does not stay in position

我正在使用Bootstrap 3,我有一個帶有導航欄的全屏旋轉木馬。 用戶完全滾動到輪播后,導航欄將固定在頂部。 這很好用。

但是現在當用戶BARELY向下滾動然后向上滾動時,導航欄不會回到原來的位置,它會保持固定在頂部。

這是我的js:

 $(function() { var lastfixed = undefined, spacerEl = undefined, fixed = false, ghostElHeight = 0; $(document).on('scroll', function() { console.log('scroll top : ' + $(window).scrollTop()); if ($(window).scrollTop() >= $(".carousel").outerHeight()) { fixed = true; if (fixed === lastfixed) return $(".navbar").addClass("navbar-fixed-top"); ghostElHeight = $(".navbar").outerHeight() if (!!!spacerEl) { spacerEl = $(".navbar").after( '<div class="navspacer" style="height:' + ghostElHeight + 'px">&nbsp;</div>').next(); } } if ($(window).scrollTop() < $(".carousel").height() + ghostElHeight) { fixed = false; if (fixed === lastfixed) return ghostElHeight = 0; $(".navbar").removeClass("navbar-fixed-top"); !!spacerEl && spacerEl.remove(); spacerEl = undefined; } lastfixed = fixed; }); }); 

我還創建了一個小提琴: http//jsfiddle.net/thqx9g9b/2/ ,以便重現你可能需要點擊滾輪的錯誤,在導航欄固定到頂部后向下滾動一點點,然后向上滾動。

奇怪的是我正在做相同的事情,但有一個全屏幕的jumbotron,並沒有出現錯誤。

更新:如果我在.carousel類上添加“padding:55px”,問題就會消失。 但如果我在旋轉木馬中使用圖像,這將導致大邊框。

這是填充的更新小提琴: http//jsfiddle.net/thqx9g9b/3/

我的版本與jumbotron一起工作的原因是因為圖像設置在父div上並且沒有填充引起的邊框,我試圖在轉盤內的各種元素上放置填充但是為了它工作它需要在父母div上,是否有人為此做過某種工作或者我錯過了什么?

你的算法目前看起來有點偏。

現在,如果你只滾動一點低於$(“。carousel”)。outerHeight()

- > fixed不會生效,因此導航欄永遠不會丟失navbar-fixed-top類。

你必須改變它

if ($(window).scrollTop() < $(".carousel").height() + ghostElHeight) {

if ($(window).scrollTop() < $(".carousel").height()) {

然后它按預期工作。 當然,你不必亂用ghostElHeight然后。 只需在HTML中添加navspacer並使用show / hide切換它。

另一個問題是:你引入了一個變量lastfixed ,這使代碼變得復雜。 沒有lastfixed更好的方法:

改變你的算法

fixed = true;
if (fixed === lastfixed) return

if (fixed == true) return
fixed = true;

對於虛假部分也是如此。 這更容易也更清晰。

完整的JS代碼:

$(function () {
    var fixed = false;

    $(document).on( 'scroll', function(){

        if($(window).scrollTop()>=$(".carousel").outerHeight())
        {
             if (fixed == true) return
             fixed = true;
             $(".navbar").addClass("navbar-fixed-top");
             $(".navspacer").show();
        }

        if($(window).scrollTop()<$(".carousel").height())
        {
             if (fixed == false) return
             fixed = false;
             $(".navbar").removeClass("navbar-fixed-top");
             $(".navspacer").hide();
        }
    });
});

並在navbar后手動添加navspacer:

<div style="height:100px; display: none;" class="navspacer">&nbsp;</div>

DEMO

暫無
暫無

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

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