Javascript 滚动到动画

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12199363/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:23:19  来源:igfitidea点击:

ScrollTo with animation

javascriptscrollto

提问by Max

how can i add an easing/animation/slowly moving to this function? At the moment it just jumps. Now it should move to the "anchor" with an animation.

我如何添加缓动/动画/缓慢移动到此功能?目前它只是跳跃。现在它应该通过动画移动到“锚点”。

<script type='text/javascript'>
        setTimeout("window.scrollBy(0,270);",3000);
</script>

采纳答案by Max

got it myself. because of wordpress and the jquery.noConflict Mode i hade to modify the code:

我自己得到了。由于 wordpress 和 jquery.noConflict 模式,我不得不修改代码:

<script type="text/javascript">
        (function($){
        $(document).ready(function(){
            setTimeout(function() {
            $('body').scrollTo( '300px', 2500 );
        }, 3000);
        });
        }(jQuery));
</script>

thanks for everybody!!!

谢谢大家!!!

回答by shunryu111

also possible with plain javascript using request animation frame..

也可以使用纯 javascript 使用请求动画框架..

// 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,
        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 PI_D2 = Math.PI / 2,
        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');

回答by Raslanove

Adapted from this answer:

改编自这个答案

function scrollBy(distance, duration) {

    var initialY = document.body.scrollTop;
    var y = initialY + distance;
    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);
}

This should allow you to smoothly scroll by the specified distance.

这应该允许您平滑滚动指定的距离。

回答by xnim

For anyone viewing this question in 2019: this can now be done natively by using

对于在 2019 年查看此问题的任何人:现在可以通过使用本机来完成

window.scrollBy({
    top: 0,
    left: 270,
    behavior: 'smooth'
});

This works in all major browsers except edge and safari. See https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy#Examples

这适用于除 edge 和 safari 之外的所有主要浏览器。请参阅https://developer.mozilla.org/en-US/docs/Web/API/Window/scrollBy#Examples

回答by piatek

Another example with jQuery, uses the easing plugin for some nice effects:

另一个 jQuery 示例,使用缓动插件来实现一些不错的效果:

http://tympanus.net/codrops/2010/06/02/smooth-vertical-or-horizontal-page-scrolling-with-jquery/

http://tympanus.net/codrops/2010/06/02/smooth-vertical-or-horizo​​ntal-page-scrolling-with-jquery/

回答by MarcoK

When using jQuery, you could easily use the .animatefunction.

使用jQuery 时,您可以轻松使用.animate函数。

Here's an example on how it should work.

这是一个关于它应该如何工作的例子。

回答by Lokesh Gamot

This will Work, Assume you need to Smooth-scrolls to the top of the page.

这将起作用,假设您需要平滑滚动到页面顶部。

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};

回答by jtheman

Using jQuery makes this much easier, perhaps with the scrollto plugin. http://flesler.blogspot.se/2007/10/jqueryscrollto.html

使用 jQuery 使这更容易,也许使用 scrollto 插件。http://flesler.blogspot.se/2007/10/jqueryscrollto.html

Consider a solution such:

考虑一个解决方案,例如:

<script type='text/javascript' src='js/jquery.1.7.2.min.js'></script>
<script type='text/javascript' src='js/jquery.scrollTo-min.js'></script>
<script type='text/javascript' src='js/jquery.easing.1.3.js'></script><!-- only for other easings than swing or linear -->
<script type='text/javascript'>
$(document).ready(function(){
    setTimeout(function() {
    $('html,body').scrollTo( {top:'30%', left:'0px'}, 800, {easing:'easeInBounce'} );
}, 3000);
});
</script>

Of course you need to dl the scripts.

当然,您需要 dl 脚本。

See http://jsfiddle.net/7bFAF/2/for a working example

有关工作示例,请参阅http://jsfiddle.net/7bFAF/2/