简体   繁体   English

如何使回到顶部锚链接平滑滚动

[英]How to make back to the top anchor link smooth scroll

i'm trying to make the back to the top button on click to be smooth scrolling but i'm stuck.. at the moment this code works but its not smooth scrolling to the top of the page.. can anyone help me on this?我试图让点击后返回顶部按钮平滑滚动,但我被卡住了..目前这段代码有效但它不能平滑滚动到页面顶部..任何人都可以帮助我解决这个问题?

<a id="BackToTop" href="#" title="Back to the top" class="back-to-top hide">
  <span>⌃</span>
</a>
<style>
  .back-to-top {
    position: fixed;
    bottom: 20px;
    right: 25px;
    color: #999;
    background-color: #243066;
    z-index: 60000;  
  }
  .back-to-top span{
     height: 47px;
  }
  .hide {
    display: none!important;
  }
  .back-to-top:hover {
    box-shadow: 1px 1px 25px #9e9e9e;
  }
</style>
<script>
  (function() {
    function trackScroll() {
      var scrolled = window.pageYOffset;
      var coords = 300;

      if (scrolled > coords) {
        goTopBtn.classList.remove('hide');
      }
      if (scrolled < coords) {
        goTopBtn.classList.add('hide');
      }
    }

    function backToTop() {
      if (window.pageYOffset > 0) {
        window.scrollBy(0, -80);
        setTimeout(backToTop, 0);
      }
    }

    var goTopBtn = document.querySelector('.back-to-top');

    window.addEventListener('scroll', trackScroll);
    goTopBtn.addEventListener('click', backToTop);
  })();
</script>

Modern browsers (everything but IE) support a scrollTo method on the window object which you can pass smooth scrolling behaviour to:现代浏览器(除 IE 之外的所有浏览器)都支持 window object 上的scrollTo方法,您可以将平滑滚动行为传递给:

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

There are also variations on this such as element.scrollIntoView()还有一些变体,例如element.scrollIntoView()

You may use that你可以用那个

document.getElementById('id').scrollIntoView({
  behavior: 'smooth'
});
document
      .getElementById("id")
      .scrollIntoView({ block: "start", behavior: "smooth" });
body{ scroll-behaviour: smooth; }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM