2017-08-11 6 views
0

これは私の機能です。私はそれにトランジションの持続時間を追加する方法を見つけることができません。それは私を真っ直ぐに持ち上げるだけです。構文は私が探しているものです。 jsについての多くのidk。遷移時間のJavaスクリプトスクロールトップ

function topFunction() { 
    document.body.scrollTop=0 ; 
    document.documentElement.scrollTop =0 ; 
} 
+0

あなたは、CSS(トランジション)を学習する必要があります、またはjQueryのようないくつかのライブラリは、[クロスブラウザのJavaScript(ではないjQueryの...)トップアニメーションへスクロール]の推移 –

+5

可能な重複(httpsであなたがやりたいです://stackoverflow.com/questions/8917921/cross-browser-javascript-not-jquery-scroll-to-top-animation) –

+0

私はcss good @JaromandaXを知っています。私が知らないことは、それをjsに埋め込む方法です。私の機能ではそれは私のページの上にそれをスクロールするものだからです。 –

答えて

1

以下のコードを使用して遷移時間を追加できます。

function topFunction() { 
    currentYOffset = self.pageYOffset; 
    initYOffset = currentYOffset; 

    var intervalId = setInterval(function(){ 
    currentYOffset -= initYOffset*0.05; 
    document.body.scrollTop = currentYOffset ; 
    document.documentElement.scrollTop = currentYOffset; 

    if(self.pageYOffset == 0){ 
     clearInterval(intervalId); 
    } 
    }, 20); 

} 

間隔の値を編集することで、トランジションのスムーズさを設定できます。私はそれを20に設定しました。

0

ここには、jQuery.animate関数を使用したjQueryソリューションがあります。

この機能を使用すると、アニメーションが適用されているセレクタだけでなく、アニメーションの時間も変更できるため、他の要素もスクロールできます。

/** 
* Scroll to a given point on the page with animation 
* 
* @param {int} scrollValue - The top position to scroll to 
* @param {int} [animationTime] - Speed of the animation (in milliseconds) 
* @param {string} [selector] - Which element to scroll. By default, it is the html/body 
*/ 
function animateScrollTo(scrollValue, animationTime, selector){ 
    if(typeof animationTime === "undefined"){ 
     animationTime = 520; 
    } 


    if(typeof selector === "undefined"){ 
     selector = "html, body"; 
    } 

    jQuery(selector).animate({scrollTop: scrollValue}, animationTime); 
} 
関連する問題