我正在寻找一个简单的,跨浏览器“滚动到顶部”的动画,我可以应用到一个链接。我不想需要一个JS库,如jQuery/Moo等。

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

对于那些在跳进图书馆之前应该100%学习JS的人来说,我是一个完美的例子。:(


当前回答

我已经选择了@timwolla answer的@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;
}

其他回答

纯javascript滚动类

这是一个老问题,但我认为我可以用一些花哨的东西和更多的选项来回答,如果你想对动画有更多的控制。

跨浏览器 复制/粘贴就绪解决方案(你只需要CSS和JS) 3种动画模式:["normal"|"linear"|false] 自定义您的动画与可用的设置-使其时髦或流畅 双击可跳过动画 每一次点击都会增加初始速度 向下拖动滚动条来停止滚动动画 通过鼠标滚轮向下停止滚动动画 动画按钮淡出滚动

这里是一个纯JS类来照顾你的滚动:

参见codepen的演示或到底部运行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>

一件容易的事。

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);
}

平滑滚动现在在所有现代浏览器中都是默认实现的。 您还可以对其进行填充,以获得旧浏览器的支持。

// Scroll to specific values
// scrollTo is the same
window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth'
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

// Scroll to a certain element
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

// Scroll certain amounts from current position for any element
document.querySelector('.scrollable-element').scrollBy({
  top: 100, 
  behavior: 'smooth'
});

// Scroll to top
var element = document.querySelector('.scrollable-element');
element.scrollBy({
  top: -element.scrollTop, 
  behavior: 'smooth'
});

来源:https://css-tricks.com/snippets/jquery/smooth-scrolling/

看来已经有很多解决方案了。不管怎样,这是另一个,使用简化方程。

// 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');

这是一种基于上述答案的跨浏览器方法

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);
  }