2017-04-22 59 views
0

我正在使用這塊jquery,可以在頁面上找到任何錨鏈接並讓我滾動到它們。它工作得很好,但我試圖弄清楚如何讓滾動緩存進出滾動。輕鬆滾動到錨鏈接?

謝謝。

//Scroll to anchors 
    $('a[href^="#"]').on('click', function(event) { 
    var target = $(this.getAttribute('href')); 
    if(target.length) { 
     event.preventDefault(); 
     $('html, body').stop().animate({ 
      scrollTop: target.offset().top -100 
     }, 1000); 
    } 

    //end of scroll code 
}); 

回答

1

的jQuery animate()需要定時功能作爲參數

語法

.animate(properties [, duration ] [, easing ] [, complete ]) 

所以,你可以添加

$('html, body').stop().animate({ 
     scrollTop: target.offset().top -100 
    }, 1500, "swing"); 

默認情況下它是swing其進展稍慢在動畫的開始和結束時比它d oes在動畫中間很像放鬆和進出。然後有linear在整個動畫中以不變的速度前進。

$('html, body').stop().animate({ 
     scrollTop: target.offset().top -100 
    }, 1500, "linear"); 

您也可以嘗試增加持續時間以緩和緩和過渡。

+0

感謝這一點,但由於某些原因,當我添加線性或擺動代碼停止工作。 – JulianJ

+0

@JulianJ你可以添加一個片段或小提琴的問題! –

+0

我在這裏爲此做了一個小提琴。正如你可以看到與擺動動畫不起作用,但如果我刪除擺動它確實工作。:https://jsfiddle.net/jsykes/9hw6bedL/3/ – JulianJ