【问题标题】:ScrollTo with animation滚动到动画
【发布时间】:2012-08-25 07:52:39
【问题描述】:

如何向此功能添加缓动/动画/缓慢移动? 此刻它只是跳跃。 现在它应该移动到带有动画的“锚点”。

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

【问题讨论】:

  • 从不将字符串传递给setInterval()setTimeout()。这样做与使用eval() 一样糟糕,一旦使用变量,它就会导致代码不可读且可能不安全,因为您需要将它们插入字符串而不是传递实际变量。正确的解决方案是setInterval(function() { /* your code *) }, msecs);。这同样适用于setTimeout()。如果只想调用单个函数不带任何参数,也可以直接传函数名:setInterval(someFunction, msecs);(注意函数名后面有no()
  • 考虑使用一些现有的库。
  • 这听起来不错,但我怎样才能在页面滚动几秒后添加时间flesler.blogspot.se/2007/10/jqueryscrollto.html

标签: javascript scrollto


【解决方案1】:

也可以使用请求动画帧的纯 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');

【讨论】:

  • 这是一个很好的答案,它帮助我想象了使用 javascript 来扩展它自己的核心功能的高级技术。谢谢!
  • 对于 IE11 支持,您可以使用 window.pageYOffset 而不是 window.scrollY
  • 是否可以将其与元素的 .scrollTop 属性一起使用?我无法让它为我工作。
  • 我希望我能投票 10 次,这正是我想要的!如果您将 targetY 计算为 targetY = window.scrollY + offset,这也适用于 scrollBy(dY) 功能
【解决方案2】:

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

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

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

【讨论】:

【解决方案3】:

改编自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);
}

这应该可以让您平滑滚动指定的距离。

【讨论】:

    【解决方案4】:

    另一个使用 jQuery 的例子,使用缓动插件来获得一些不错的效果:

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

    【讨论】:

      【解决方案5】:

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

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

      谢谢大家!!!

      【讨论】:

        【解决方案6】:

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

        Here's an example on how it should work.

        【讨论】:

          【解决方案7】:

          这可行,假设您需要平滑滚动到页面顶部。

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

          【讨论】:

          • 这会完成吗?基本上,你在做c = c * 7/8,它永远不会真正触及0,对吧?它将收敛到0,由于精度有限,它最终可能会被JS四舍五入到0,但仍然如此。
          【解决方案8】:

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

          考虑这样的解决方案:

          <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>
          

          当然你需要 dl 脚本。

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

          【讨论】:

          • 我如何添加时间,页面应该在几秒后滚动?
          • 使用 jQuery,您可以轻松地使用超时,就像您建议自己设置延迟一样,例如:stackoverflow.com/questions/1836105/…
          • 我试过这个..但它不起作用。code code
          • @max "elasout" 缓动仅在演示页面上定义。除了默认的摆动或线性版本之外的其他缓动,您将需要缓动插件,如我上面的示例。另请注意,我编辑了函数以使用 timeout() 而不是 delay() 因为 delay() 仅适用于本机 jQuery 效果。使用 timeout() 更通用。
          • 他的文档准备功能有问题。 cl.ly/image/0X02160j2x0gcl.ly/image/0a0m1f3c0a3a
          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-07-06
          相关资源
          最近更新 更多