JavaScript 动画平滑滚动

标签 javascript

默认情况下,当您有这样的片段链接时:

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

浏览器立即向下滚动到该片段。我该如何编程才能使用标准 JS 顺利地向下移动到该片段?

这是一个例子:

Example (要查看工作示例,只需单击 3 个圆圈内的 3 个箭头即可观看平滑的动画滚动)

最佳答案

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

<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 动画平滑滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19268039/

相关文章:

javascript - React.map 已定义但显示未定义

javascript - 使用 jquery 的问答游戏

javascript - 作为参数传递时如何调用函数引用

javascript - CSS 文件在 Chrome 中有效,但在 IE 中无效?

javascript - 如何使用 html javascript jquery 自动显示包含图像的文件夹?

javascript - ASP.NET 上的简单 jquery 无法在 Firefox 上运行

javascript - 为什么我的正则表达式没有通过这种情况(包括代码)

javascript - 从 URL 获取参数值

javascript - 使用 javascript 将 var 分配给输入标记的 name 属性

javascript - Handlebars @first 不适用于 Ember.js 1.0.0