簡體   English   中英

滾動后jQuery動畫的長時間延遲

[英]Long delay with jquery animation after scroll

我有一個div ,寬度為0px 用戶滾動x距離后,我想將div動畫140px

當我滾動到該點時,在看到動畫之前會有很長的延遲。 我滾動的越遠,延遲越長。 我也將包含div設置為固定在同一點。 固定項目可以正常工作,但動畫總是會延遲:

HTML:

<div class="menu-bar">
    <div class="wrap">
        <div id="menu-logo">
            <img src="..." />
        </div>
        <nav id="site-navigation" role="navigation">...</nav>

        <div class="right-menu">...</div>
    </div>
</div>

JS:

$(window).scroll(function(){
    var barPos = $('#content').offset().top - $(document).scrollTop();
    var menuHeight = $('.menu-bar').height();
    var topColors = $('#top-colors').height();

    if(barPos <= (topColors+menuHeight)) {
        $('.menu-bar').css({'position':'fixed','bottom':'auto','top':'0px'});
        $('#menu-logo').animate({'width':'140px'});
    } else {
        $('.menu-bar').css({'position':'absolute','bottom':'0px','top':'auto'});
        $('#menu-logo').animate({'width':'0px'});
    }
});

當文檔視圖或元素已滾動時,將觸發滾動事件。

這意味着,您的回調將觸發多次,因此每個jQuery.fn.animate都會在隊列中添加一個新動畫。

作為快速修復,您可以嘗試在每次jQuery.fn.animate調用之前調用jQuery.fn.clearQueuejQuery.fn.stop

您可以在JQuery的css聲明中更改動畫以進行過渡:

$(window).scroll(function(){
   var barPos = $('#content').offset().top - $(document).scrollTop();
   var menuHeight = $('.menu-bar').height();
   var topColors = $('#top-colors').height();

   if(barPos <= (topColors+menuHeight)) {
      $('.menu-bar').css({
        'position':'fixed',
        'bottom':'auto',
        'top':'0px',
        'width': '140px',
        'transition': 'width 0.4s ease'
   });
   } else {
      $('.menu-bar').css({
        'position':'absolute',
        'bottom':'0px',
        'top':'auto'
        'width': '0',
        'transition': 'width 0.4s ease'
     });
   }
});

暫無
暫無

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

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