CSS - scroll-behavior 属性



CSS 的 scroll-behavior 属性控制当用户点击链接或使用滚动条时浏览器滚动的方式。

可能的值

  • auto − 默认值。此值允许浏览器使用其默认的滚动行为。

  • smooth − 此值在您点击链接时创建平滑的滚动效果。

应用于

滚动框。

DOM 语法

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

CSS 滚动条行为 - Auto 值

以下示例演示如何使用 scroll-behavior: 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 滚动条行为 - Smooth 值

以下示例演示如何使用 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> 
广告