2017-02-09 59 views
1

我有一個div,我要顯示在滾動和背部,但沒有達到預期其工作的用戶滾動時隱藏。問題是,當我向下滾動然後顯示正常,但是當我向後滾動時,隱藏延遲。JQuery的動畫速度問題

我要的是顯示div與從上到下滑動,和隱藏在底部到頂部的效果。

這是我一直在努力代碼:

$(window).scroll(function() { 
 
    var fheader = $(".top-header"); 
 
    if ($(this).scrollTop()>50) 
 
    { 
 
     $(fheader).animate({top: "0px"},{duration: 100, easing: "linear"}); 
 
    } 
 
    else 
 
    { 
 
     $(fheader).animate({top: "-50px"},{duration: 100, easing: "linear"}); 
 
    } 
 
});
.top-header { 
 
    width: 100%; 
 
    position: fixed; 
 
    height: 50px; 
 
    background: #fff; 
 
    border-bottom: 2px solid #ccc; 
 
    top: -50px; 
 
    left: 0; 
 
} 
 
.content { 
 
    width: 100%; 
 
    height: 1400px; 
 
    float: left; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="top-header"> 
 
    header 
 
</div> 
 
<div class="content"> 
 
    this is content 
 
</div>

+2

標準問題 - 以SO搜索細節。您需要*刪除*滾動事件,因爲您在每個滾動條上勾選動畫。例如,如果向下滾動,在開始滾動之前它會滾動滾動100次 - 每個動畫需要在下一個動畫之前完成。當您停止滾動時,去抖只會觸發一次。在處理程序中添加一個'console.log(「scroll」)',你會看到它多頻繁地發射。 –

+0

另一種方法是存儲上一個滾動位置,看它現在是超過/低於限制,並且只在上/下而不是每次調用時應用動畫。 –

回答

2

animate前只需添加stop()防止隊列執行:

這裏是一個工作示例:

$(window).scroll(function() { 
 
    var fheader = $(".top-header"); 
 
    if ($(this).scrollTop()>50) 
 
    { 
 
     $(fheader).stop().animate({top: "0px"},{duration: 100, easing: "linear"}); 
 
    } 
 
    else 
 
    { 
 
     $(fheader).stop().animate({top: "-50px"},{duration: 100, easing: "linear"}); 
 
    } 
 
});
.top-header { 
 
    width: 100%; 
 
    position: fixed; 
 
    height: 50px; 
 
    background: #fff; 
 
    border-bottom: 2px solid #ccc; 
 
    top: -50px; 
 
    left: 0; 
 
} 
 
.content { 
 
    width: 100%; 
 
    height: 1400px; 
 
    float: left; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="top-header"> 
 
    header 
 
</div> 
 
<div class="content"> 
 
    this is content 
 
</div>

+1

非常感謝,它的工作完美如預期! –

+0

不客氣;) –