JavaScript动画平滑滚动 [英] JavaScript animated smooth-scroll

查看:99
本文介绍了JavaScript动画平滑滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

默认情况下,如果你有这样的片段链接:

By default when you have fragment links like this:

<a href="/some-url#some-fragment">some text</a>

浏览器只是立即向下滚动到该片段。如何使用标准JS将其编程为平滑地移动到该片段?

the browser just, scrolls down to that fragment instantly. How do i program it to smoothly move down to that fragment with standard JS?

以下是一个示例:

示例(要查看工作示例,只需点击3个圆圈内的3个箭头,观看流畅的动画滚动)

Example (To see the working example, just click on the 3 arrows inside the 3 circles and watch the smooth animated scrolling)

推荐答案

好吧,我想我找到了答案,发布了在这里帮助其他有类似疑问的人:

okay, i think i found my answer, posting it here to help others with the similar doubt:

<html>
  <head>
    <script type="text/javascript">
      var singleton = {};
      var timeout = singleton;

      window.onscroll = windowScroll;

      function windowScroll ()
      {
        var toTop = document.getElementById('toTop');
        toTop.style.display = ((window.scrollY > 0) ? "block" : "none");
      }

      function scrollStep ()
      {
        var y1 = window.scrollY - 1000;
        window.scrollTo(0, y1);

        if (y1 > 0)
        {
          timeout = window.setTimeout(scrollStep, 100);  
        }
        else if (timeout != singleton)
        {
          window.clearTimeout(timeout);   
        }
      }
    </script>

    <style type="text/css">
      #toTop {
        display: block;
        position: fixed;
        bottom: 20px;
        right: 20px;
        font-size: 48px;
      }

      #toTop {
        -moz-transition: all 0.5s ease 0s;
        -webkit-transition: all 0.5s ease 0s;
        -o-transition: all 0.5s ease 0s;
        transition: all 0.5s ease 0s;
        opacity: 0.5;
        display: none;
        cursor: pointer;
      }

      #toTop:hover {
        opacity: 1;
      }
    </style>
  </head>

  <body>
    <p id="top">your text here</p>
    <a href="#top" onclick="scrollStep(); return false" id="toTop"
       ><img src="images/go-to-top.png" alt="Go to top" title="Go to top"></a>
  </body>
</html>

这篇关于JavaScript动画平滑滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆