CSS 属性

CSS scroll-behavior属性控制当用户单击链接或使用滚动条时浏览器滚动的平滑程度。

属性值

  • auto: 默认值。该值允许浏览器使用其默认滚动行为。

  • smooth: 当您单击链接时,该值会创建平滑的滚动效果。

适用范围

滚动框。

DOM 语法

object.style.scrollBehavior: "auto|smooth"; 

CSS scroll-behavior: auto

以下内容示例演示如何使用滚动行为:auto 属性 -

<html>
<head>
<style>
   nav {
      background-color: rgb(67, 238, 45);
      padding: 5px;
      text-align: center;
      width: 300px;
   }
   nav a {
      margin:5px;
      text-decoration: none;
   }
   .scroll-behavior-auto {
      background-color: #F1EFB0;
      height: 150px;
      overflow: auto;
      scroll-behavior: auto;
      text-align: center;
      width: 300px;
      padding: 5px;
   }
   .scrolling-section {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
   }
</style>
</head>
<body>
   <nav>
      <a href="#section1">Topic 1</a>
      <a href="#section2">Topic 2</a>
      <a href="#section3">Topic 3</a>
   </nav>
   <div class="scroll-behavior-auto">
      <div class="scrolling-section" id="section1">Topic 1</div>
      <div class="scrolling-section" id="section2">Topic 2</div>
      <div class="scrolling-section" id="section3">Topic 3</div>
   </div>
</body>
</html> 

CSS scroll-behavior: smooth 

以下示例演示如何使用滚动行为:平滑属性 -

<html>
<head>
<style>
   nav {
      background-color: rgb(67, 238, 45);
      padding: 5px;
      text-align: center;
      width: 300px;
   }
   nav a {
      margin:5px;
      text-decoration: none;
   }
   .scroll-behavior-auto {
      background-color: #F1EFB0;
      height: 150px;
      overflow: auto;
      scroll-behavior: smooth;
      text-align: center;
      width: 300px;
      padding: 5px;
   }
   .scrolling-section {
      display: flex;
      align-items: center;
      justify-content: center;
      height: 100%;
   }
</style>
</head>
<body>
   <nav>
      <a href="#section1">Topic 1</a>
      <a href="#section2">Topic 2</a>
      <a href="#section3">Topic 3</a>
   </nav>
   <div class="scroll-behavior-auto">
      <div class="scrolling-section" id="section1">Topic 1</div>
      <div class="scrolling-section" id="section2">Topic 2</div>
      <div class="scrolling-section" id="section3">Topic 3</div>
   </div>
</body>
</html>