크로스 브라우저 JavaScript (jQuery가 아님) 맨 위로 스크롤


222

링크에 적용 할 수있는 간단한 크로스 브라우저 "스크롤 맨 위로"애니메이션을 찾고 있습니다. jQuery / Moo 등과 같은 JS 라이브러리가 필요하지 않습니다.

// jQuery Equivilant to convert to pure JS...
$('html, body').animate({scrollTop:0}, 400);

나는 도서관에 뛰어 들기 전에 JS 100 %를 배워야했던 사람에게 완벽한 사례입니다. :(


78
jQuery를 사용 하지 않으려는 경우 +1 , 유효한 이유 :) 영감을주기 위해 이러한 라이브러리의 소스 코드 (예 : jquery-1.7.1.js)를 살펴볼 수 있습니다.
Rob W

1
여기를 참조하십시오 : stackoverflow.com/questions/1144805/…
Oyeme

10
@seand JavaScript는 jQuery가 아니지만 jQuery는 JavaScript입니다. OP와 같은 사람이 JavaScript를 배우고 싶다면 JavaScript로 동일한 코드를 작성하는 방법을 알지 못한다면 부풀린 라이브러리를 건드리지 않아야합니다.
Rob W

3
jQuery와 같은 라이브러리를 사용하는 @RobW는 브라우저 간 차이점을 추상화하는 데 도움이되므로 웹 개발에 중요한 것으로 간주합니다. 완벽하게 훌륭한 구현이 존재하고 자유롭게 이용할 수 있다면 이러한 차이점을 알 필요는 없습니다.
seand

6
@seand는 우리가 엉터리 코더를 만드는 방법입니다. 그들은 언어를 이해하지 못하지만, 알고 있기 때문에 무제한의 jQuery 코드를 생성 할 수 있습니다. 이로 인해 DOM에 모든 것을 저장하는 것과 같은 해킹이 발생합니다 (때로는 변수 이외의 변수가 무엇인지조차 알지 못하기 때문에 var something = $(...)) var veryBigObject = {...}. 함수의 최상위는 성능을 살해 할 것입니다). 그리고 종종 언어의 이름이 jQuery가 아닌 Javascript인지조차 모릅니다.
Killah

답변:


139
function scrollTo(element, to, duration) {
    if (duration <= 0) return;
    var difference = to - element.scrollTop;
    var perTick = difference / duration * 10;

    setTimeout(function() {
        element.scrollTop = element.scrollTop + perTick;
        if (element.scrollTop === to) return;
        scrollTo(element, to, duration - 10);
    }, 10);
}

데모:

function runScroll() {
  scrollTo(document.body, 0, 600);
}
var scrollme;
scrollme = document.querySelector("#scrollme");
scrollme.addEventListener("click",runScroll,false)

function scrollTo(element, to, duration) {
  if (duration <= 0) return;
  var difference = to - element.scrollTop;
  var perTick = difference / duration * 10;

  setTimeout(function() {
    element.scrollTop = element.scrollTop + perTick;
    if (element.scrollTop == to) return;
    scrollTo(element, to, duration - 10);
  }, 10);
}
<p>Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.  Very long page.Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page. Very long page.
</p>
<button id=scrollme type="button">To the top</button>


11
document.documentElement대신 document.body(CSS :를 설정하지 않는 한 body{height:100%;}). 이 개념을 사용한 실무 데모 : jsfiddle.net/S5ALP/1
Rob W

7
@RobW 귀하의 추가 기능은 여기에서 작동하지 않습니다. @ Chrome @ Ubuntu Linux
TimWolla

2
Firefox 9.0, Ubuntu에서도 마찬가지입니다 :). 귀하의 코드는 Firefox에서 실패했지만 Chrome에서 작동했습니다. 제 코드는 Chrome에서 실패했지만 FF에서는 작동했습니다.
Rob W

2
즉되어야합니다if (duration <= 0) return;
존 Koops

4
top.window.scroll(0, value)대신 사용하도록 수정하면 element.scrollTop = valueChrome과 Firefox (우분투)에서 모두 작동합니다. :)
Shomz

113

이미 많은 솔루션이있는 것 같습니다. 어쨌든 여기 또 다른 하나는 여유 방정식을 사용합니다.

// first add raf shim
// http://www.paulirish.com/2011/requestanimationframe-for-smart-animating/
window.requestAnimFrame = (function(){
  return  window.requestAnimationFrame       ||
          window.webkitRequestAnimationFrame ||
          window.mozRequestAnimationFrame    ||
          function( callback ){
            window.setTimeout(callback, 1000 / 60);
          };
})();

// main function
function scrollToY(scrollTargetY, speed, easing) {
    // scrollTargetY: the target scrollY property of the window
    // speed: time in pixels per second
    // easing: easing equation to use

    var scrollY = window.scrollY || document.documentElement.scrollTop,
        scrollTargetY = scrollTargetY || 0,
        speed = speed || 2000,
        easing = easing || 'easeOutSine',
        currentTime = 0;

    // min time .1, max time .8 seconds
    var time = Math.max(.1, Math.min(Math.abs(scrollY - scrollTargetY) / speed, .8));

    // easing equations from https://github.com/danro/easing-js/blob/master/easing.js
    var easingEquations = {
            easeOutSine: function (pos) {
                return Math.sin(pos * (Math.PI / 2));
            },
            easeInOutSine: function (pos) {
                return (-0.5 * (Math.cos(Math.PI * pos) - 1));
            },
            easeInOutQuint: function (pos) {
                if ((pos /= 0.5) < 1) {
                    return 0.5 * Math.pow(pos, 5);
                }
                return 0.5 * (Math.pow((pos - 2), 5) + 2);
            }
        };

    // add animation loop
    function tick() {
        currentTime += 1 / 60;

        var p = currentTime / time;
        var t = easingEquations[easing](p);

        if (p < 1) {
            requestAnimFrame(tick);

            window.scrollTo(0, scrollY + ((scrollTargetY - scrollY) * t));
        } else {
            console.log('scroll done');
            window.scrollTo(0, scrollTargetY);
        }
    }

    // call it once to get started
    tick();
}

// scroll it!
scrollToY(0, 1500, 'easeInOutQuint');

10
누군가가 다행입니다requestAnimationFrame
Lucas

4
투표하여 답변으로 선택해야합니다. 이것은 크로스 브라우저로 작동하는 유일한 것입니다
wlingke

requestAnimationFrame모든 브라우저와 호환되지 않는 일부 모바일 장치는 동적 솔루션이 아닙니다. developer.mozilla.org/en-US/docs/Web/API/window/…
SUB-HDR

1
스 니펫 상단의 @ SUB-HDR은 requestAnimationFrame브라우저의 비 호환성을 처리해야하는 shim 이 있습니다.
shunryu111

페이지에 Firefox에 많은 이미지가있는 섹션이있을 때 애니메이션이 매우
게으르게됩니다.

79
window.scroll({top: 0, left: 0, behavior: 'smooth' });

부드러운 스크롤 에 관한 기사에서 얻었습니다 .

필요한 경우 일부 폴리 필을 사용할 수 있습니다.


4
이것이 jQuery 솔루션이라고 생각했기 때문에 거의 다운 투표되었습니다. 그 기사는 혼란스럽게 분류됩니다! 또한, 나는 그것이 또한 scrollIntoView({behavior: 'smooth'})존재하고 사람들이 이런 종류의 문제에 필요한 것을 할 수 있다고 지적하고 싶었습니다 .
Brendan

1
최신 Chrome에서 오류가 발생합니다Uncaught TypeError: Failed to execute 'scroll' on 'Window': No function was found that matched the signature provided.
rorymorris89

1
@Sgnl은 이것이 수정되었음을 확인할 수 있습니다. 좋은 오래된 Chrome 업데이트가 깨짐 :)
rorymorris89

4
왜 이것이 더 많은 표를 얻지 못했는지, 100000 줄의 코드가없는 간단한 스크롤! 감사합니다!
스모키 도슨

4
이 답변은 허용 된 답변으로 표시되어야합니다. 커스텀 트랜지션 기능을 사용하지 않는 내장 접근법. 감사합니다!
Sagar

70

나는 2 차 인-아웃 여유 (약간 더 매끄럽게)를 사용하도록 TimWolla의 답변을 수정했습니다. 다음은 실제 예입니다. on jsFiddle . 여유 기능은 여기에서 제공됩니다 : Robert Penner의 여유 기능

document.getElementsByTagName('button')[0].onclick = function () {
    scrollTo(document.body, 0, 1250);   
}

function scrollTo(element, to, duration) {
    var start = element.scrollTop,
        change = to - start,
        increment = 20;

    var animateScroll = function(elapsedTime) {        
        elapsedTime += increment;
        var position = easeInOut(elapsedTime, start, change, duration);                        
        element.scrollTop = position; 
        if (elapsedTime < duration) {
            setTimeout(function() {
                animateScroll(elapsedTime);
            }, increment);
        }
    };

    animateScroll(0);
}

function easeInOut(currentTime, start, change, duration) {
    currentTime /= duration / 2;
    if (currentTime < 1) {
        return change / 2 * currentTime * currentTime + start;
    }
    currentTime -= 1;
    return -change / 2 * (currentTime * (currentTime - 2) - 1) + start;
}

5
파이어 폭스에서는 코드가 작동하지 않습니다. 이것에 대한 해결책이 있습니까?
Milos

2
@Milos "scrollTo (document.documentElement, 0, 1250);"를 사용하십시오. "scrollTo (document.body, 0, 1250);"대신 Firefox와 Chrome 모두에서 작동합니다.
Daniel

왜 수학을 사용하고 있습니까? 수학 없이는 데모를 진행 중입니다
bCliks

2
@Daniel document. documentElement은 Chrome에서 작동하지 않습니다.
15:33에

@ bCliks, 그것은 완화 방법입니다
Clayton Graul

27

JQuery 코드가 없으면 도움이되기를 바랍니다.

function TopscrollTo() {
if(window.scrollY!=0)
{
    setTimeout(function() {
       window.scrollTo(0,window.scrollY-30);
        TopscrollTo();
    }, 100);
   }
}

버튼 클릭 이벤트 또는 원하는 다른 요소 / 이벤트 에서이 TopscrollTo () 함수 를 호출 하십시오.


19

더 많은 옵션과 일부 이동 기능을 추가하기 위해 @TimWolla의 코드를 수정했습니다. 또한 document.body.scrollTopdocument.documentElement.scrollTop을 사용 하여 크로스 브라우저에 대한 지원이 추가되었습니다.

// scroll to top
scrollTo(0, 1000);

// Element to move, time in ms to animate
function scrollTo(element, duration) {
    var e = document.documentElement;
    if(e.scrollTop===0){
        var t = e.scrollTop;
        ++e.scrollTop;
        e = t+1===e.scrollTop--?e:document.body;
    }
    scrollToC(e, e.scrollTop, element, duration);
}

// Element to move, element or px from, element or px to, time in ms to animate
function scrollToC(element, from, to, duration) {
    if (duration <= 0) return;
    if(typeof from === "object")from=from.offsetTop;
    if(typeof to === "object")to=to.offsetTop;

    scrollToX(element, from, to, 0, 1/duration, 20, easeOutCuaic);
}

function scrollToX(element, xFrom, xTo, t01, speed, step, motion) {
    if (t01 < 0 || t01 > 1 || speed<= 0) {
        element.scrollTop = xTo;
        return;
    }
    element.scrollTop = xFrom - (xFrom - xTo) * motion(t01);
    t01 += speed * step;

    setTimeout(function() {
        scrollToX(element, xFrom, xTo, t01, speed, step, motion);
    }, step);
}
function easeOutCuaic(t){
    t--;
    return t*t*t+1;
}

http://jsfiddle.net/forestrf/tPQSv/

축소 버전 : http://jsfiddle.net/forestrf/tPQSv/139/

// c = element to scroll to or top position in pixels
// e = duration of the scroll in ms, time scrolling
// d = (optative) ease function. Default easeOutCuaic
function scrollTo(c,e,d){d||(d=easeOutCuaic);var a=document.documentElement;if(0===a.scrollTop){var b=a.scrollTop;++a.scrollTop;a=b+1===a.scrollTop--?a:document.body}b=a.scrollTop;0>=e||("object"===typeof b&&(b=b.offsetTop),"object"===typeof c&&(c=c.offsetTop),function(a,b,c,f,d,e,h){function g(){0>f||1<f||0>=d?a.scrollTop=c:(a.scrollTop=b-(b-c)*h(f),f+=d*e,setTimeout(g,e))}g()}(a,b,c,0,1/e,20,d))};
function easeOutCuaic(t){
    t--;
    return t*t*t+1;
}

그리고 1 / durationscrollToX를 처음 호출 할 때 의 요점은 무엇입니까 ?
Jessica

t01은 0에서 1까지 증가하는 시간입니다. 1에 도달하면 크롤이 종료됩니다. 나는 2 년 전에 이것을했다. 나는 모든 것을 기억하지 못한다. 미안하다.
Forestrf

11

사용하지 않고이 작업을 수행 할 수있는 순수 자바 스크립트 방법 실제로 존재 setTimeout하거나 requestAnimationFrame또는 jQuery를이.

간단히 말해서 scrollView에서 스크롤하려는 요소를 찾고 scrollIntoView를 사용하십시오.

el.scrollIntoView({behavior:"smooth"});

여기에 plunkr가 있습니다.


가장 좋은 답변 : 한 줄의 코드, 가장 짧고 효과적인;)
Jacopo Pace

1
전달 scrollIntoViewOption시 브라우저 간 지원이 제공되지 않습니다. developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
WebWanderer

9

이 답변 에서 적응 :

function scroll(y, duration) {

    var initialY = document.documentElement.scrollTop || document.body.scrollTop;
    var baseY = (initialY + y) * 0.5;
    var difference = initialY - baseY;
    var startTime = performance.now();

    function step() {
        var normalizedTime = (performance.now() - startTime) / duration;
        if (normalizedTime > 1) normalizedTime = 1;

        window.scrollTo(0, baseY + difference * Math.cos(normalizedTime * Math.PI));
        if (normalizedTime < 1) window.requestAnimationFrame(step);
    }
    window.requestAnimationFrame(step);
}

이를 통해 어디서나 지정된 "y"로 부드럽게 스크롤 (코사인 기능) 할 수 있습니다.


9

CSS 속성 스크롤 동작을 언급 한 사람은 없습니다.

CSS

html {
  scroll-behavior: smooth;
}

JS

window.scrollTo(0,0)

이것은 놀라운 일입니다! 모든 브라우저에서 지원되는 것은 아니지만 제대로 돌아 가기 때문에 괜찮습니다.
Swimburger

예수님, 이것이 내 평생 어디에 있었습니까?
Mitya

8

순수 자바 스크롤러 클래스

이것은 오래된 질문이지만 애니메이션을 조금 더 제어하고 싶다면 멋진 것들과 더 많은 옵션으로 대답 할 수 있다고 생각했습니다.

  • 크로스 브라우저
  • 복사 / 붙여 넣기 준비 솔루션 (CSS 및 JS 만 필요)
  • 3 가지 애니메이션 모드 : [ "normal"| "linear"| false]
  • 사용 가능한 설정으로 애니메이션을 사용자 정의하십시오.
  • 애니메이션을 건너 뛰려면 두 번 클릭
  • 매번 클릭 할 때마다 초기 속도가 추가됩니다
  • 스크롤 막대를 아래로 끌어 스크롤 애니메이션을 중지하십시오.
  • 마우스 휠을 아래로 스크롤 애니메이션 중지
  • 스크롤시 애니메이션 버튼 페이드 인
  • 다음은 스크롤을 처리하는 순수한 JS 클래스입니다.

    SEE DEMO AT CODEPEN 또는 GO TO 바닥 및 프로그램 실행 SINPET

    // ------------------- USE EXAMPLE ---------------------
    // *Set options
    var options = {
      'showButtonAfter': 200, // show button after scroling down this amount of px
      'animate': "linear", // [false|normal|linear] - for false no aditional settings are needed
    
      'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms
        'steps': 20, // the more steps per loop the slower animation gets
        'ms': 10 // the less ms the quicker your animation gets
      }, 
      'linear': { // applys only if [animate: linear] - set scroll px|ms
        'px': 30, // the more px the quicker your animation gets
        'ms': 10 // the less ms the quicker your animation gets
      }, 
    };
    
    
    // *Create new Scroller and run it.
    var scroll = new Scroller(options);
    scroll.init();

    전체 수업 스크립트 + 사용 예 :

    // PURE JAVASCRIPT (OOP)
    
    function Scroller(options) {
      this.options = options;
      this.button = null;
      this.stop = false;
    }
    
    Scroller.prototype.constructor = Scroller;
    
    Scroller.prototype.createButton = function() {
    
      this.button = document.createElement('button');
      this.button.classList.add('scroll-button');
      this.button.classList.add('scroll-button--hidden');
      this.button.textContent = "^";
      document.body.appendChild(this.button);
    }
    
    Scroller.prototype.init = function() {
      this.createButton();
      this.checkPosition();
      this.click();
      this.stopListener();
    }
    
    Scroller.prototype.scroll = function() {
      if (this.options.animate == false || this.options.animate == "false") {
        this.scrollNoAnimate();
        return;
      }
      if (this.options.animate == "normal") {
        this.scrollAnimate();
        return;
      }
      if (this.options.animate == "linear") {
        this.scrollAnimateLinear();
        return;
      }
    }
    Scroller.prototype.scrollNoAnimate = function() {
      document.body.scrollTop = 0;
      document.documentElement.scrollTop = 0;
    }
    Scroller.prototype.scrollAnimate = function() {
      if (this.scrollTop() > 0 && this.stop == false) {
        setTimeout(function() {
          this.scrollAnimate();
          window.scrollBy(0, (-Math.abs(this.scrollTop()) / this.options.normal['steps']));
        }.bind(this), (this.options.normal['ms']));
      }
    }
    Scroller.prototype.scrollAnimateLinear = function() {
      if (this.scrollTop() > 0 && this.stop == false) {
        setTimeout(function() {
          this.scrollAnimateLinear();
          window.scrollBy(0, -Math.abs(this.options.linear['px']));
        }.bind(this), this.options.linear['ms']);
      }
    }
    
    Scroller.prototype.click = function() {
    
      this.button.addEventListener("click", function(e) {
        e.stopPropagation();
        this.scroll();
      }.bind(this), false);
    
      this.button.addEventListener("dblclick", function(e) {
        e.stopPropagation();
        this.scrollNoAnimate();
      }.bind(this), false);
    
    }
    
    Scroller.prototype.hide = function() {
      this.button.classList.add("scroll-button--hidden");
    }
    
    Scroller.prototype.show = function() {
      this.button.classList.remove("scroll-button--hidden");
    }
    
    Scroller.prototype.checkPosition = function() {
      window.addEventListener("scroll", function(e) {
        if (this.scrollTop() > this.options.showButtonAfter) {
          this.show();
        } else {
          this.hide();
        }
      }.bind(this), false);
    }
    
    Scroller.prototype.stopListener = function() {
    
      // stop animation on slider drag
      var position = this.scrollTop();
      window.addEventListener("scroll", function(e) {
        if (this.scrollTop() > position) {
          this.stopTimeout(200);
        } else {
          //...
        }
        position = this.scrollTop();
      }.bind(this, position), false);
    
      // stop animation on wheel scroll down
      window.addEventListener("wheel", function(e) {
        if (e.deltaY > 0) this.stopTimeout(200);
      }.bind(this), false);
    }
    
    Scroller.prototype.stopTimeout = function(ms) {
      this.stop = true;
      // console.log(this.stop); //
      setTimeout(function() {
        this.stop = false;
        console.log(this.stop); //
      }.bind(this), ms);
    }
    
    Scroller.prototype.scrollTop = function() {
      var curentScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
      return curentScrollTop;
    }
    
    
    
    // ------------------- USE EXAMPLE ---------------------
    // *Set options
    var options = {
      'showButtonAfter': 200, // show button after scroling down this amount of px
      'animate': "normal", // [false|normal|linear] - for false no aditional settings are needed
    
      'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms
        'steps': 20, // the more steps per loop the slower animation gets
        'ms': 10 // the less ms the quicker your animation gets
      },
      'linear': { // applys only if [animate: linear] - set scroll px|ms
        'px': 30, // the more px the quicker your animation gets
        'ms': 10 // the less ms the quicker your animation gets
      },
    };
    // *Create new Scroller and run it.
    var scroll = new Scroller(options);
    scroll.init();
    /* CSS */
    
    @import url(https://fonts.googleapis.com/css?family=Open+Sans);
     body {
      font-family: 'Open Sans', sans-serif;
      font-size: 1.2rem;
      line-height: 2rem;
      height: 100%;
      position: relative;
      padding: 0 25%;
    }
    .scroll-button {
      font-size: 1.2rem;
      line-height: 2rem;
      padding: 10px;
      width: 50px;
      height: 50px;
      background: black;
      color: white;
      border-radius: 50%;
      position: fixed;
      right: 20px;
      bottom: 20px;
      visibility: visible;
      filter: alpha(opacity=50);
      filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=50);
      opacity: 0.5;
      cursor: pointer;
      transition: all 1.2s;
      -webkit-transition: all 1.2s;
      -moz-transition: all 1.2s;
      -ms-transition: all 1.2s;
      -o-transition: all 1.2s;
    }
    .scroll-button:hover {
      filter: alpha(opacity=100);
      filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=100);
      opacity: 1;
    }
    .scroll-button--hidden {
      filter: alpha(opacity=0);
      filter: progid: DXImageTransform.Microsoft.Alpha(Opacity=0);
      opacity: 0;
      visibility: hidden;
    }
    <!-- HTML -->
    
    <h1>Scroll down by 200px for button to appear</h1>
    <ul>
      <li>Cross-browser</li>
      <li>Copy/Paste solution</li>
      <li>3 animate modes: <b>["normal"|"linear"|false]</b></li>
      <li>Customize your aniamtion with aveilable settings - make it snapy or fluent</li>
      <li>Double click to skip animation</li>
      <li>Every next single click adds initial speed</li>
      <li>Stop scroll animation by draging down the scroll bar</li>
      <li>Stop scroll animation by mouse wheel down</li>
      <li>Animated button fade-in-out on scroll</li>
    </ul>
    
    <br />
    <br />
    <pre>
    // ------------------- USE EXAMPLE ---------------------
    // *Set options
    var options = {
      'showButtonAfter': 200, // show button after scroling down this amount of px
      'animate': "normal", // [false|normal|linear] - for false no aditional settings are needed
      
      'normal': { // applys only if [animate: normal] - set scroll loop distanceLeft/steps|ms
        'steps': 20, // the more steps the slower animation gets
        'ms': 20 // the less ms the quicker your animation gets
      }, 
      'linear': { // applys only if [animate: linear] - set scroll px|ms
        'px': 55, // the more px the quicker your animation gets
        'ms': 10 // the less ms the quicker your animation gets
      }, 
    };
    
    // *Create new Scroller and run it.
    var scroll = new Scroller(options);
    scroll.init();
    </pre>
    <br />
    <br />
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quae molestiae illo nobis quo autem molestias voluptatum quam, amet ipsum debitis, iure animi illum soluta eaque qui perspiciatis harum, sequi nesciunt.</span><span>Quisquam nesciunt aspernatur a possimus pariatur enim architecto. Hic aperiam sit repellat doloremque vel est soluta et assumenda dolore, sint sapiente porro, quam impedit. Sint praesentium quas excepturi, voluptatem dicta!</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate, porro nisi molestias minima corrupti tempore, dolorum fugiat ipsam dicta doloremque accusamus atque consequatur iusto natus, mollitia distinctio odit dolor tempora.</span><span>Perferendis a in laudantium accusantium, dolorum eius placeat velit porro similique, eum cumque veniam neque aspernatur architecto suscipit rem laboriosam voluptates laborum? Voluptates tempora necessitatibus animi nostrum quod, maxime odio.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nihil accusantium, itaque corporis repellat pariatur soluta officia perspiciatis in reprehenderit facere, incidunt saepe excepturi. Inventore atque ex illo, ipsam at deserunt.</span><span>Laborum inventore officia, perspiciatis cumque magni consequatur iste accusantium soluta, nesciunt blanditiis voluptatibus adipisci laudantium mollitia minus quia necessitatibus voluptates. Minima unde quos impedit necessitatibus aspernatur minus maiores ipsa eligendi!</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate nesciunt, explicabo similique, quo maxime modi, aliquid, voluptatibus repellendus dolorum placeat mollitia ea dicta quia laboriosam alias dignissimos ipsam tenetur. Nulla.</span><span>Vel maiores necessitatibus odio voluptate debitis, error in accusamus nulla, eum, nemo et ea commodi. Autem numquam at, consequatur temporibus. Mollitia placeat nobis blanditiis impedit distinctio! Ad, incidunt fugiat sed.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsam voluptatum, odio quam omnis iste laudantium, itaque architecto, eos ullam debitis delectus sapiente nemo autem reprehenderit. Dolorem quidem facere ipsam! Nisi.</span><span>Vitae quaerat modi voluptatibus ratione numquam? Sapiente aliquid officia pariatur quibusdam aliquam id expedita non recusandae, cumque deserunt asperiores. Corrupti et doloribus aspernatur ipsum asperiores, ipsa unde corporis commodi reiciendis?</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima adipisci minus iste, nesciunt itaque quisquam quidem voluptatum assumenda rerum aliquid, excepturi voluptatem tempora. Possimus ratione alias a error vel, rem.</span><span>Officia esse error accusantium veritatis ad, et sit animi? Recusandae mollitia odit tenetur ad cumque maiores eligendi blanditiis nobis hic tempora obcaecati consequatur commodi totam, debitis, veniam, ducimus molestias ut.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Obcaecati quibusdam, tempora cupiditate quaerat tempore ullam delectus voluptates optio eum placeat provident consequatur iure reprehenderit vero quae sapiente architecto earum nemo.</span><span>Quis molestias sint fuga doloribus, necessitatibus nulla. Esse ipsa, itaque asperiores. Tempora a sequi nobis cumque incidunt aspernatur, pariatur rem voluptatibus. Atque veniam magnam, ea laudantium ipsum reprehenderit sapiente repellendus.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Minima, pariatur at explicabo aliquid repudiandae vero eum quasi totam voluptates iusto unde ad repellendus ipsam et voluptatem hic adipisci! Vero, nobis!</span><span>Consequatur eligendi quo quas omnis architecto dolorum aperiam doloremque labore, explicabo enim incidunt vitae saepe, quod soluta illo odit provident amet beatae quasi animi. Similique nostrum molestiae animi corrupti qui?</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Molestias quis, tempora laborum incidunt qui fuga adipisci doloremque iusto commodi vitae est, nemo iure placeat ut sit optio, consequuntur voluptas impedit.</span><span>Eos officiis, hic esse unde eaque, aut tenetur voluptate quam sint vel exercitationem totam dolor odio soluta illo praesentium non corrupti! Consequuntur velit, mollitia excepturi. Minus, veniam accusantium! Aliquam, ea!</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Reprehenderit quis reiciendis veritatis expedita velit vitae amet magni sunt rerum in blanditiis aut tempore quia fugiat, voluptates officia quaerat quam id.</span><span>Sapiente tempore repudiandae, quae doloremque ullam odio quia ea! Impedit atque, ipsa consequatur quis obcaecati voluptas necessitatibus, cupiditate sunt amet ab modi illum inventore, a dolor enim similique architecto est!</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Itaque non aliquam, sit illo quas deserunt esse nobis reprehenderit quidem fuga beatae eligendi reiciendis omnis qui repellat velit earum blanditiis possimus.</span><span>Provident aspernatur ducimus, illum beatae debitis vitae non dolorum rem officia nostrum natus accusantium perspiciatis ad soluta maiores praesentium eveniet qui hic quis at quaerat ea perferendis. Ut, aut, natus.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ratione corrupti quibusdam, sed hic veniam. Perspiciatis ex, quod architecto natus autem totam at commodi excepturi maxime pariatur corporis, veritatis vero, praesentium.</span><span>Nesciunt suscipit, nobis eos perferendis ex quaerat inventore nihil qui magnam saepe rerum velit reiciendis ipsam deleniti ducimus eligendi odio eius minima vero, nisi voluptates amet eaque, iste, labore laudantium.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illo, voluptas accusantium ad omnis velit distinctio! Adipisci magnam nihil nostrum molestiae rem dolores, ut ad nemo, dolor quos itaque maiores quaerat!</span><span>Quia ad suscipit reprehenderit vitae inventore eius non culpa maiores omnis sit obcaecati vel placeat quibusdam, ipsa exercitationem nam odit, magni nobis. Quam quas, accusamus expedita molestiae asperiores eaque ex?</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Rerum explicabo doloribus nihil iusto quasi vel expedita dignissimos amet mollitia, temporibus aut atque architecto assumenda dolorum nam velit deserunt totam numquam.</span><span>Ab perferendis labore, quae. Quidem architecto quo officia deserunt ea doloribus libero molestias id nisi perferendis eum porro, quibusdam! Odit aliquid placeat rem aut officia minus sit esse eos obcaecati!</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eligendi nostrum repellendus placeat, unde aperiam. Fuga, voluptas, minima. Debitis nemo ducimus itaque laboriosam error quaerat reprehenderit quo animi incidunt. Nulla, quis!</span><span>Explicabo assumenda dicta ratione? Tempora commodi asperiores, explicabo doloremque eius quia impedit possimus architecto sit nemo odio eum fuga minima dolor iste mollitia sequi dolorem perspiciatis unde quisquam laborum soluta.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Veniam officia corporis, reiciendis laudantium, voluptate voluptates necessitatibus assumenda, delectus quisquam velit deserunt! Reprehenderit, vel quaerat accusantium nesciunt libero animi. Sequi, eveniet?</span><span>Animi natus pariatur porro, alias, veniam aut est tempora adipisci molestias harum modi cumque assumenda enim! Expedita eveniet autem illum rerum nostrum ipsum alias neque aut, dolorum impedit pariatur non?</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quis aliquid rerum, odio veniam ipsam ad officia quos repellat ex aperiam voluptatum optio est animi possimus minus. Sapiente voluptates amet dolorem.</span><span>Illo necessitatibus similique asperiores inventore ut cumque nihil assumenda debitis explicabo rerum, dolorum molestiae culpa accusantium. Nisi doloremque optio provident blanditiis, eum ipsam asperiores, consequatur aliquam vel sit mollitia sunt.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Enim, totam harum perferendis. Minus ea perferendis laboriosam, iste, qui corrupti, quas veritatis omnis officiis animi fuga perspiciatis impedit! Error, harum, voluptas.</span><span>Omnis laborum, cum mollitia facilis ipsa unde distinctio maxime nesciunt illum perspiciatis ut officiis, eligendi numquam dolorem quod modi ipsam est rerum perferendis repellendus totam. Maxime excepturi culpa alias labore.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Impedit deleniti, odit sit consequatur dolorum omnis repellendus, alias vel ullam numquam. Nostrum obcaecati hic, possimus delectus nam atque aliquid explicabo cum.</span><span>Explicabo tenetur minima consequatur, aliquam, laudantium non consequuntur facilis sint, suscipit debitis ex atque mollitia magni quod repellat ratione dolorum excepturi molestiae cumque iusto eos unde? Voluptatum dolores, porro provident!</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At laboriosam fuga aperiam eveniet, obcaecati esse, nulla porro iure molestiae praesentium sint fugiat ea voluptate suscipit voluptates mollitia, voluptatibus. Autem, non.</span><span>Numquam velit culpa tempora ratione ipsum minus modi in? Nisi reiciendis, voluptate voluptatem maxime repellat quae odio, repellendus aliquid laborum dolorem. Labore, fuga ea minima explicabo quae voluptatum necessitatibus, similique.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi, rerum dolorum nemo error fugiat ut, modi, architecto libero maxime laborum repellendus doloribus neque aperiam adipisci quaerat obcaecati deserunt consequuntur amet!</span><span>Sint, assumenda nisi obcaecati doloremque iste. Perspiciatis accusantium, distinctio impedit cum esse recusandae sunt. Officiis culpa dolore eius, doloribus natus, dolorum excepturi vitae fugiat ullam provident harum! Suscipit, assumenda, harum.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Odit, nihil tenetur tempore eligendi qui nesciunt consequatur delectus accusantium consectetur ipsa, nulla doloribus dolores rerum corporis, laborum, laboriosam hic mollitia repellat.</span><span>Ab deleniti vitae blanditiis quod tenetur! Voluptatem temporibus ab eaque quis? Quis odio aliquid harum temporibus totam, ipsa eius iusto fugiat enim in, quibusdam molestiae aliquam consequatur nulla, consequuntur sint.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Illum odit praesentium quos, earum nesciunt laudantium illo tempora eligendi, porro doloremque mollitia neque aperiam inventore nam maxime dolor labore aspernatur molestias.</span><span>Voluptatibus provident hic cupiditate placeat, ut reprehenderit nisi eum, dolores ad sed quis. Doloribus molestiae, quae rem odit expedita soluta, facilis animi corporis velit ut in, recusandae harum laboriosam veritatis.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Incidunt repudiandae molestias magnam delectus veritatis labore, corporis dicta officia quos, ad corrupti odit! Ad hic officia maxime eveniet consectetur similique adipisci!</span><span>Quia at, nesciunt aliquid delectus ex alias voluptas maxime hic esse. Incidunt, laborum quos mollitia dolores et! Voluptas commodi asperiores, fugit quidem quis corporis, a eaque, animi, autem deserunt repellendus.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sequi quas, voluptas hic minima inventore optio, id quidem placeat necessitatibus omnis voluptatibus vitae mollitia tempora consequuntur consequatur, illo facilis accusamus illum.</span><span>Voluptates consequuntur ipsam odit. Eius quis ipsam vitae, nihil molestias perferendis corporis recusandae consequatur vero iure blanditiis quas adipisci quos voluptatem rem illo voluptate. Eveniet officiis iure sit laborum veniam.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Suscipit a quis cumque nostrum quisquam molestiae pariatur, asperiores natus necessitatibus adipisci illum cupiditate nam vero, tempora excepturi laborum, earum. Voluptates, nobis.</span><span>Pariatur suscipit, hic blanditiis libero, iusto, quam cupiditate nam error id asperiores repellat ab consequatur vitae ipsa voluptatem totam magni reiciendis expedita maxime dolor! Minus explicabo quas, laborum ab omnis!</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Labore qui ad assumenda placeat optio illo molestias corporis dolorum cum. Doloribus eius autem obcaecati minima, asperiores iure dignissimos ducimus suscipit dolorem.</span><span>Blanditiis earum accusamus eaque temporibus necessitatibus voluptatum dolorem enim debitis inventore assumenda quae error perspiciatis aut, nulla delectus quam ipsa sapiente ea aliquam laboriosam repudiandae. Nesciunt praesentium, beatae eos quasi!</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cupiditate dicta voluptate impedit? Ad voluptatum dicta earum perferendis asperiores. Dolore distinctio modi expedita consequatur provident perspiciatis neque totam rerum placeat quas.</span><span>Eveniet optio est possimus iste accusantium ipsum illum. Maiores saepe repudiandae facere, delectus iure dolorem vitae nihil pariatur minima, reprehenderit eligendi dolore impedit, nisi doloribus quidem similique. Optio, delectus, minus.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Iste ex molestiae architecto enim nihil tempore, atque consequuntur doloribus recusandae sed consequatur veniam quos, in consectetur perspiciatis magni nostrum ab voluptates.</span><span>Nisi quos mollitia quis in maiores asperiores labore deserunt! Voluptate voluptas adipisci qui hic officia molestias, laborum necessitatibus sint nam vel minus incidunt perspiciatis recusandae sunt, rerum suscipit doloremque possimus!</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. At nihil perferendis quae quidem facilis aliquid pariatur possimus hic asperiores, recusandae exercitationem adipisci atque laborum, delectus, odit ab reprehenderit distinctio dolor.</span><span>Non excepturi quos aspernatur repudiandae laboriosam, unde molestias, totam, sapiente harum accusamus delectus laborum ipsam velit amet nisi! Consectetur aliquam provident voluptatibus saepe repudiandae eveniet laborum beatae, animi, voluptate dolores.</span></p>
    <p><span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Cumque magni, eum ipsa, veritatis facere voluptatem dolorum nobis neque minus debitis asperiores iste. Pariatur sequi quam, tempora. Dignissimos, esse similique tempora.</span><span>Ex delectus excepturi autem sunt, nemo repudiandae, recusandae nostrum accusantium nobis temporibus magnam eligendi similique veritatis deleniti, eaque blanditiis possimus at! Repellat alias laboriosam ipsum commodi dolorem, corporis dolore suscipit!</span></p>


    1
    자세히 살펴보면 매우 간단합니다. 아마도 실제보다 조금 더 복잡한 것처럼 보이게하는 것은 OOP 일 것입니다. 다른 스 니펫에는 차단 기능이 포함되지 않습니다. 그래서 나는 조금 더 많은 complet을 게시했습니다. 당신이 그것에 대해 신경 쓰지 않으면 내 솔루션은 당신의 요구에 대해 약간 위로 볼 수 있습니다. FF 및 IE에서 작동하게하려면 CSS에 접두사를 추가하면됩니다. 다른 사람이 요청하면 고칠 것입니다. CSS를 "복사 / 붙여 넣기"솔루션으로 만들고 싶었 기 때문에 CSS를 추가했습니다. 나는 이것이 그보다 더 쉬울 수 있다고 생각하지 않습니다 :-).
    DevWL

    좋아, 이것은 접두사 문제는 아니지만 :) 어쨌든 수정하겠습니다.
    DevWL

    문제 해결됨. 이제 IE, FF 및 Chrome에서 작동합니다. 여기에서 발생하는 작업 : "document.documentElement.scrollTop"Firefox 및 IE에서는 작동하지만 Chrome에서는 작동하지 않습니다. "document.body.scrollTop"는 Chrome에서는 작동하지만 Firefox에서는 작동하지 않습니다. IE에서. 이 문제를 해결하기 위해 새로운 메소드 [scrollTop ()]이 클래스 프로토 타입에 구현되었습니다. 새 메소드는 브라우저에서 작동하는 값 관련 값을 리턴합니다. // var curentScrollTop = document.documentElement.scrollTop || document.body.scrollTop; // curentScrollTop을 반환합니다.
    DevWL

    또 다른 IE 버그가 수정되었습니다. classList.add ( 'class1, class2'); class1 만 적용하고 class2는 무시됩니다. 수정 : classList.add ( 'class1'); classList.add ( 'class2'); IE를로드하면 지금 버튼이 숨겨집니다.
    DevWL

    6

    쉬운.

    var scrollIt = function(time) {
        // time = scroll time in ms
        var start = new Date().getTime(),
            scroll = document.documentElement.scrollTop + document.body.scrollTop,
            timer = setInterval(function() {
                var now = Math.min(time,(new Date().getTime())-start)/time;
                document.documentElement.scrollTop
                    = document.body.scrollTop = (1-time)/start*scroll;
                if( now == 1) clearTimeout(timer);
            },25);
    }

    아니면 그냥 window.scrollTo(x, y);.
    Rob W

    3
    그래도 애니메이션되지는 않습니다.
    암흑의 절대 군 Niet

    .scrollTop및에 대한 대체 옵션을 제공했습니다 .scrollLeft.
    Rob W

    @NiettheDarkAbsol 이것은 body.scrolltop과 documentElement.scrolltop을 신경 쓰는 함수입니다. 스크롤 사용 안함, 세미콜론 누락 등의 오류가 있습니다. 수정 해주세요.
    Deniz Porsuk

    @DenizPorsuk "스크롤을 사용하지 않습니다"라는 말이 맞습니다 *scroll. 스크롤 위치를 계산할 때였습니다. 그러나, 나는 빠진 것이 보이지 않습니다 ;...
    어두운

    2

    이 자바 스크립트 전용 솔루션을 아래에서 만들었습니다.

    간단한 사용법 :

    EPPZScrollTo.scrollVerticalToElementById('wrapper', 0);

    엔진 객체 (필터, fps 값으로 바이올린을 칠 수 있음) :

    /**
     *
     * Created by Borbás Geri on 12/17/13
     * Copyright (c) 2013 eppz! development, LLC.
     *
     * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
     * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
     * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
     *
     */
    
    
    var EPPZScrollTo =
    {
        /**
         * Helpers.
         */
        documentVerticalScrollPosition: function()
        {
            if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari.
            if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode).
            if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8.
            return 0; // None of the above.
        },
    
        viewportHeight: function()
        { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; },
    
        documentHeight: function()
        { return (document.height !== undefined) ? document.height : document.body.offsetHeight; },
    
        documentMaximumScrollPosition: function()
        { return this.documentHeight() - this.viewportHeight(); },
    
        elementVerticalClientPositionById: function(id)
        {
            var element = document.getElementById(id);
            var rectangle = element.getBoundingClientRect();
            return rectangle.top;
        },
    
        /**
         * Animation tick.
         */
        scrollVerticalTickToPosition: function(currentPosition, targetPosition)
        {
            var filter = 0.2;
            var fps = 60;
            var difference = parseFloat(targetPosition) - parseFloat(currentPosition);
    
            // Snap, then stop if arrived.
            var arrived = (Math.abs(difference) <= 0.5);
            if (arrived)
            {
                // Apply target.
                scrollTo(0.0, targetPosition);
                return;
            }
    
            // Filtered position.
            currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter);
    
            // Apply target.
            scrollTo(0.0, Math.round(currentPosition));
    
            // Schedule next tick.
            setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps));
        },
    
        /**
         * For public use.
         *
         * @param id The id of the element to scroll to.
         * @param padding Top padding to apply above element.
         */
        scrollVerticalToElementById: function(id, padding)
        {
            var element = document.getElementById(id);
            if (element == null)
            {
                console.warn('Cannot find element with id \''+id+'\'.');
                return;
            }
    
            var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding;
            var currentPosition = this.documentVerticalScrollPosition();
    
            // Clamp.
            var maximumScrollPosition = this.documentMaximumScrollPosition();
            if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition;
    
            // Start animation.
            this.scrollVerticalTickToPosition(currentPosition, targetPosition);
        }
    };

    8
    정말요? 이 괴물 같은 코드를 만드는 것은 로켓 발사기를 사용하여 비행을 죽이는 것과 같습니다.
    Killah

    3
    @Killah 저는 간단한 사용법과 가독성에만 관심이 있습니다. 원하는 경우 축소하여 게시 할 수 있습니다. :)
    Geri Borbás

    내가 말하고자하는 것은 거기에 너무 많은 도우미 함수가 있다는 것입니다 (왜 한 번 사용되는 도우미 함수가 필요합니까?). console.warn그리고 문자열 매개 변수 setTimeout는 프로덕션 코드에 적합하지 않습니다 (두 번째 함수는 거의 적합하지 않습니다) eval기본적으로 있기 때문에 어디서나 ).
    Killah

    1
    함수 호출이 고가의 물건이 아니라고 가정하면 모든 것을 주석 처리하는 대신 명명 된 함수에 코드를 추출하는 것이 좋습니다. 따라서 적어도 나에게 코드를 더 잘 읽을 수 있으며 클라이언트 코드는 10 줄 더 짧을 수 있습니다.
    Geri Borbás

    2

    여기에 대한 답변 중 일부를 기반으로하지만 사인 곡선을 사용하여 부드러운 전환을 위해 간단한 수학을 사용하십시오.

    scrollTo(element, from, to, duration, currentTime) {
           if (from <= 0) { from = 0;}
           if (to <= 0) { to = 0;}
           if (currentTime>=duration) return;
           let delta = to-from;
           let progress = currentTime / duration * Math.PI / 2;
           let position = delta * (Math.sin(progress));
           setTimeout(() => {
               element.scrollTop = from + position;
               this.scrollTo(element, from, to, duration, currentTime + 10);
           }, 10);
       }

    용법:

    // Smoothly scroll from current position to new position in 1/2 second.
    scrollTo(element, element.scrollTop, element.scrollTop + 400, 500, 0);

    추신. ES6 스타일에 주목


    1

    이것은 위의 답변을 기반으로 한 크로스 브라우저 접근 방식입니다

    function scrollTo(to, duration) {
        if (duration < 0) return;
        var scrollTop = document.body.scrollTop + document.documentElement.scrollTop;
        var difference = to - scrollTop;
        var perTick = difference / duration * 10;
    
        setTimeout(function() {
          scrollTop = scrollTop + perTick;
          document.body.scrollTop = scrollTop;
          document.documentElement.scrollTop = scrollTop;
          if (scrollTop === to) return;
          scrollTo(to, duration - 10);
        }, 10);
      }

    좋은 대답입니다! 당신과 무슨 일이 일어나고 있는지 설명해 주시겠습니까 differenceperTick?
    Jessica

    1

    또 다른 접근법은 window.scrollBy를 사용하는 것입니다.

    JSFiddle

    function scroll(pxPerFrame, duration) {
            if (!pxPerFrame || !duration) return;
            const end = new Date().getTime() + duration;
            step(); 
    
            function step() {
              window.scrollBy(0, pxPerFrame);
              if (new Date().getTime() < end) {
                window.setTimeout(step, 1000 / 60);
              } else {
                console.log('done scrolling'); 
              }
            }
          }
    body {
      width: 200px;
    }
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
    <p>
    <button onclick="scroll(-5, 3000)">
    scroll(-5, 3000)
    </button>
    </p>


    1

    @timwolla 응답의 @akai 버전을 선택하고 stopAnimation 함수를 추가하여 새 애니메이션을 시작하기 전에 이전 애니메이션을 중지 할 수 있습니다.

    if ( this.stopAnimation )
        this.stopAnimation()
    
        this.stopAnimation = scrollTo( el, scrollDestination, 300 )
    
    
    // definitions
    
    function scrollTo(element, to, duration) {
        var start = element.scrollTop,
            change = to - start,
            increment = 20,
            timeOut;
    
        var animateScroll = function(elapsedTime) {        
            elapsedTime += increment;
            var position = easeInOut(elapsedTime, start, change, duration);                        
            element.scrollTop = position; 
            if (elapsedTime < duration) {
                timeOut = setTimeout(function() {
                    animateScroll(elapsedTime);
                }, increment);
            }
        };
    
        animateScroll(0);
    
        return stopAnimation
    
        function stopAnimation() {
            clearTimeout( timeOut )
        }
    }
    
    function easeInOut(currentTime, start, change, duration) {
        currentTime /= duration / 2;
        if (currentTime < 1) {
            return change / 2 * currentTime * currentTime + start;
        }
        currentTime -= 1;
        return -change / 2 * (currentTime * (currentTime - 2) - 1) + start;
    }

    0

    위의 솔루션을 기반으로 한 또 다른 크로스 브라우저 접근 방식

    function doScrollTo(to, duration) {
        var element = document.documentElement;
    
            var start = element.scrollTop,
            change = to - start,
            increment = 20,
            i = 0;
    
        var animateScroll = function(elapsedTime) {
            elapsedTime += increment;
            var position = easeInOut(elapsedTime, start, change, duration);
            if (i === 1 && window.scrollY === start) {
                element = document.body;
                start = element.scrollTop;
            }
            element.scrollTop = position;
            if (!i) i++;
            if (elapsedTime < duration) {
                setTimeout(function() {
                    animateScroll(elapsedTime);
                }, increment);
            }
        };
    
        animateScroll(0);
    }

    트릭은 실제 스크롤 변경을 제어하고 0이면 스크롤 요소를 변경하는 것입니다.


    -1

    아래로 선형 스크롤 애니메이션. 순수 JS, JQuery 없음 어쩌면 내 솔루션이 누군가에게 도움이 될 것입니다.

    let action_count = 8;
    let speed_ms = 15;
    let objDiv = document.getElementsByClassName('js_y5_area3').item(0);
    
    let scroll_height = objDiv.scrollHeight;
    let window_height = objDiv.offsetHeight;
    
    let scroll_top = objDiv.scrollTop;
    let need_scroll_top = scroll_height - window_height;
    
    if (scroll_top < need_scroll_top)
    {
        let step = Math.ceil((need_scroll_top - scroll_top) / action_count);
    
        let scrollInterval = setInterval(function()
        {
            scroll_top += step;
            objDiv.scrollTop = scroll_top;
    
            if (scroll_top >= need_scroll_top)
            {
                clearInterval(scrollInterval);
            }
    
        }, speed_ms);
    }

    당신은 변수를 변경할 수 있습니다 action_count, speed_ms당신의 취향에 애니메이션을 스크롤 구성 할 수 있습니다.


    -2

    이 솔루션을 사용하십시오

    animate(document.documentElement, 'scrollTop', 0, 200);

    감사


    불행히도 이것은 브라우저 간 능숙하지 않은 것 같습니다. :(
    Lucas Morgan

    당신은 단지 "document.documentElemen"에 대한 장소에서 올바른 DOM 요소를 찾을 필요가 @LucasMorgan 원하는대로 정장 당신
    록쉬 식당

    1
    없는 한 animate()창 범위에 기능 ... 잘못 이해합니다. 이 Element.animate()기능은 많은 브라우저에서 인식되지 않습니다. developer.mozilla.org/en-US/docs/Web/API/Element/animate
    Lucas Morgan

    그러나 나는 오해했다. jquery 함수에 대해 이야기합니다. 질문에 jquery가 없기 때문에 jquery를 가져 오지 않을 것이라고 가정했습니다. 내 잘못이야!
    Lucas Morgan

    -3

    위의 게시물 중 대부분 / 전부가 자바 스크립트가있는 버튼을 검색한다는 것을 알았습니다. 버튼이 하나만 있으면 작동합니다. 버튼 안에 "onclick"요소를 정의하는 것이 좋습니다. 그런 다음 "onclick"은 스크롤을 발생시키는 함수를 호출합니다.

    그렇게하면 버튼이 다음과 같이 보이는 한 하나 이상의 버튼을 사용할 수 있습니다.

    <button onclick="scrollTo(document.body, 0, 1250)">To the top</button>

    3
    애니메이션되지 않습니다.
    dmackerman
    당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
    Licensed under cc by-sa 3.0 with attribution required.