目录

如何 - 平滑滚动


了解如何使用 CSS 创建平滑的滚动效果。


平滑滚动

第1节

单击链接即可查看 "smooth" 滚动效果。

单击我平滑滚动到下面的第 2 部分

注意:删除滚动行为属性以删除平滑滚动。


平滑滚动

添加scroll-behavior: smooth添加到 <html> 元素以实现整个页面的平滑滚动(注意:也可以将其添加到特定元素/滚动容器):

示例

html {
  scroll-behavior: smooth;
}
亲自试一试 »

浏览器支持

表中的数字指定完全支持滚动行为属性的第一个浏览器版本。

Property
scroll-behavior 61.0 79.0 36.0 14.0 48.0


跨浏览器解决方案

对于不支持的浏览器scroll-behavior属性,您可以使用 JavaScript 或 JavaScript 库,例如jQuery,创建适用于所有浏览器的解决方案:

示例

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  // Add smooth scrolling to all links
  $("a").on('click', function(event) {

    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 800, function(){

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });
});
</script>
亲自试一试 »

提示:在我们的 CSS 参考中了解有关滚动行为属性的更多信息:CSS 滚动行为属性