CSS - scroll-behavior 属性



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

可能的值

  • auto − 默认值。此值允许浏览器使用其默认滚动行为。
  • smooth - 当您单击链接时,此值会创建平滑的滚动效果。

适用于

滚动框。

DOM 语法


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

CSS 滚动条行为 - 自动值

以下示例演示了如何使用 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 滚动条行为 - 平滑值

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