2016-04-14 12 views
1

バニラJavaScriptを使用してスムーズに要素にスクロールしようとするときに問題が発生します。バニラJavaScriptを使用してスムーズに要素にスクロールする

私は3つのリンクを持つ1ページのウェブサイトを持っています。リンクの1つをクリックすると、そのリンクが表すセクションにスムーズにスクロールできます。私はjQueryバージョンを持っていますが、これはうまくいっていますが、バニラJavaScriptを使って同じ結果を得る方法を学びたいと思います。

質問は以前聞かれましたが、回答は少し複雑です。よりクリーンで簡単な答えがあるはずです。

ありがとうございました。

のjQueryコード:

$('a').click(function(){ 
    $('html, body').animate({ 
     scrollTop: $($(this).attr('href')).offset().top 
    }, 1000); 
    return false; 
}); 
+0

はフィドルを提供します。 –

+0

私はjQueryコードと同じ結果を達成したいと思いますが、バニラのJavascriptを使用しています。私はそれを達成する方法を説明することができません。 Javascriptをよく知っている人がコードを書くことができたら、私はそれを感謝します。 – NoName84

答えて

4

あなたがスムーズバニラJSスクロールのためのいくつかのイージング関数をする必要があります。

Robert Pennerは私がHTML5のコースのためにいくつかの時間前にやったdemo on jsbinを持っ緩和男

です。ソースに興味があるかもしれません。上記の例で使用されるスクロール用

デモ機能:?正確に間違っている何

function scrollToItemId(containerId, srollToId) { 

     var scrollContainer = document.getElementById(containerId); 
     var item = document.getElementById(scrollToId); 

     //with animation 
     var from = scrollContainer.scrollTop; 
     var by = item.offsetTop - scrollContainer.scrollTop; 
     if (from < item.offsetTop) { 
      if (item.offsetTop > scrollContainer.scrollHeight - scrollContainer.clientHeight) { 
       by = (scrollContainer.scrollHeight - scrollContainer.clientHeight) - scrollContainer.scrollTop; 
      } 
     } 

     var currentIteration = 0; 

     /** 
     * get total iterations 
     * 60 -> requestAnimationFrame 60/second 
     * second parameter -> time in seconds for the animation 
     **/ 
     var animIterations = Math.round(60 * 0.5); 

     (function scroll() { 
      var value = easeOutCubic(currentIteration, from, by, animIterations); 
      scrollContainer.scrollTop = value; 
      currentIteration++; 
      if (currentIteration < animIterations) { 
       requestAnimationFrame(scroll); 
      }  
     })(); 

     //without animation 
     //scrollContainer.scrollTop = item.offsetTop; 

    } 

    //example easing functions 
    function linearEase(currentIteration, startValue, changeInValue, totalIterations) { 
     return changeInValue * currentIteration/totalIterations + startValue; 
    } 
    function easeOutCubic(currentIteration, startValue, changeInValue, totalIterations) { 
     return changeInValue * (Math.pow(currentIteration/totalIterations - 1, 3) + 1) + startValue; 
    } 
+0

答えmichaPauありがとう。そこにはもっと簡単なやり方がありますか? – NoName84

関連する問題