平滑滚动

Avatar of Chris Coyier
Chris Coyier

嘿!在你深入研究基于 JavaScript 的平滑滚动之前,要知道为此有一个原生的 CSS 功能:scroll-behavior

html {
  scroll-behavior: smooth;
}

而且,在你使用 jQuery 等库来帮助你之前,也存在一个平滑滚动的原生 JavaScript 版本,例如这样

// Scroll to specific values
// scrollTo is the same
window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth'
});

// Scroll certain amounts from current position 
window.scrollBy({ 
  top: 100, // could be negative value
  left: 0, 
  behavior: 'smooth' 
});

// Scroll to a certain element
document.querySelector('.hello').scrollIntoView({ 
  behavior: 'smooth' 
});

Dustan Kasten 为此提供了一个 polyfill。并且你可能只会在你使用滚动页面来完成无法使用 #target 跳转链接和 CSS 完成的操作时才会用到它。

平滑滚动的可访问性

无论你使用哪种技术进行平滑滚动,可访问性都是一个需要关注的问题。例如,如果你点击一个 #hash 链接,浏览器的原生行为是将焦点更改到与该 ID 匹配的元素。页面可能会滚动,但滚动是焦点更改的副作用。

如果你覆盖了默认的焦点更改行为(你必须这样做才能防止立即滚动并启用平滑滚动),你需要自己处理焦点更改

Heather Migliorisi平滑滚动和可访问性 中写到了这一点,并提供了代码解决方案。

使用 jQuery 实现平滑滚动

jQuery 也可以做到这一点。以下是在同一页面上执行到锚点的平滑页面滚动的代码。它内置了一些逻辑来识别这些跳转链接,而不是目标其他链接。

// Select all links with hashes
$('a[href*="#"]')
  // Remove links that don't actually link to anything
  .not('[href="#"]')
  .not('[href="#0"]')
  .click(function(event) {
    // On-page links
    if (
      location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 
      && 
      location.hostname == this.hostname
    ) {
      // Figure out element to scroll to
      var target = $(this.hash);
      target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
      // Does a scroll target exist?
      if (target.length) {
        // Only prevent default if animation is actually gonna happen
        event.preventDefault();
        $('html, body').animate({
          scrollTop: target.offset().top
        }, 1000, function() {
          // Callback after animation
          // Must change focus!
          var $target = $(target);
          $target.focus();
          if ($target.is(":focus")) { // Checking if the target was focused
            return false;
          } else {
            $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
            $target.focus(); // Set focus again
          };
        });
      }
    }
  });

如果你使用了这段代码,并且你像 HEY WHAT’S WITH THE BLUE OUTLINES?! 一样,请阅读上面关于可访问性的内容。

React 中的平滑滚动

James Quick 提供了一个关于如何使用 react-scroll 插件在 React 中实现平滑滚动的不错的 分步教程

<Link
  activeClass="active"
  to="section1"
  spy={true}
  smooth={true}
  offset={-70}
  duration={500}
>