programing tip

jquery없는 scrollTop 애니메이션

itbloger 2020. 10. 12. 07:19
반응형

jquery없는 scrollTop 애니메이션


jQuery를 사용하지 않고 애니메이션 "위로 스크롤"효과를 만들려고합니다.

jQuery에서는 일반적으로 다음 코드를 사용합니다.

$('#go-to-top').click(function(){ 
      $('html,body').animate({ scrollTop: 0 }, 400);
      return false; 
});

jQuery를 사용하지 않고 scrollTop을 어떻게 애니메이션합니까?


HTML :

<button onclick="scrollToTop(1000);"></button>

1 # 자바 스크립트 (선형) :

function scrollToTop(scrollDuration) {
    var scrollStep = -window.scrollY / (scrollDuration / 15),
        scrollInterval = setInterval(function(){
        if ( window.scrollY != 0 ) {
            window.scrollBy( 0, scrollStep );
        }
        else clearInterval(scrollInterval); 
    },15);
}

2 # 자바 스크립트 (Ease in and out) :

function scrollToTop(scrollDuration) {
const   scrollHeight = window.scrollY,
        scrollStep = Math.PI / ( scrollDuration / 15 ),
        cosParameter = scrollHeight / 2;
var     scrollCount = 0,
        scrollMargin,
        scrollInterval = setInterval( function() {
            if ( window.scrollY != 0 ) {
                scrollCount = scrollCount + 1;  
                scrollMargin = cosParameter - cosParameter * Math.cos( scrollCount * scrollStep );
                window.scrollTo( 0, ( scrollHeight - scrollMargin ) );
            } 
            else clearInterval(scrollInterval); 
        }, 15 );
}

노트 :

  • 밀리 초 단위의 기간 (1000ms = 1 초)
  • 두 번째 스크립트는 cos 함수를 사용합니다. 곡선의 예 :

여기에 이미지 설명 입력

많은 찬성 투표자들로 인해 몇 년 전에 작성한 코드를 다시 확인하고 최적화하려고했습니다. 더 나아가 코드 하단에 약간의 수학적 설명을 추가했습니다.

업데이트 (쉬움 및 아웃) :

더 부드러운 슬라이드 / 애니메이션을 위해 requestAnimationFrame 메서드를 사용합니다. (브라우저가 넓은 영역을 다시 그려야하기 때문에 큰 창에서 약간의 끊김이 발생합니다)

function scrollToTop(scrollDuration) {
    var cosParameter = window.scrollY / 2,
        scrollCount = 0,
        oldTimestamp = performance.now();
    function step (newTimestamp) {
        scrollCount += Math.PI / (scrollDuration / (newTimestamp - oldTimestamp));
        if (scrollCount >= Math.PI) window.scrollTo(0, 0);
        if (window.scrollY === 0) return;
        window.scrollTo(0, Math.round(cosParameter + cosParameter * Math.cos(scrollCount)));
        oldTimestamp = newTimestamp;
        window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}
/* 
    Explanations:
    - pi is the length/end point of the cosinus intervall (see above)
    - newTimestamp indicates the current time when callbacks queued by requestAnimationFrame begin to fire.
      (for more information see https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)
    - newTimestamp - oldTimestamp equals the duration

      a * cos (bx + c) + d                      | c translates along the x axis = 0
    = a * cos (bx) + d                          | d translates along the y axis = 1 -> only positive y values
    = a * cos (bx) + 1                          | a stretches along the y axis = cosParameter = window.scrollY / 2
    = cosParameter + cosParameter * (cos bx)    | b stretches along the x axis = scrollCount = Math.PI / (scrollDuration / (newTimestamp - oldTimestamp))
    = cosParameter + cosParameter * (cos scrollCount * x)
*/

참고 URL : https://stackoverflow.com/questions/21474678/scrolltop-animation-without-jquery

반응형