如何使用 CSS 建立滑動效果?
透過 scroll-behavior 屬性可以在網頁中設定滑動效果。將屬性值設定為 smooth(平滑)。透過在點選按鈕時實現滑動效果來檢查這一點,即透過點選頂部的按鈕到達下面的部分,反之亦然。讓我們瞭解一下如何使用 HTML 和 CSS 建立滑動效果。
網頁滑動效果
首先,在 <html> 下設定 scroll-behavior 屬性以為整個網頁實現該屬性 −
html {
scroll-behavior: smooth;
}
設定兩個部分
這兩個部分被設定為兩個單獨的 div。一個在頂部,另一個在第一個部分的下面 −
<div id="firstSection"> <h2>Top</h2> <a href="#secondSection">Click Here to Smooth Scroll Below</a> </div> <div id="secondSection"> <h2>Bottom</h2> <a href="#firstSection">Click Me to Smooth Scroll Above</a> </div>
為頂部部分設定樣式
第一個部分的高度設定為 100vh −
#firstSection {
height: 100vh;
background-color: rgb(119, 77, 219);
color: white;
padding: 20px;
}
為底部部分設定樣式
底部部分就在第一個部分的下面。針對高度,為本部分也設定了相同的屬性值 −
#secondSection {
height: 100vh;
color: white;
background-color: rgb(42, 128, 168);
padding: 20px;
}
示例
使用 CSS 建立滑動效果的程式碼如下 −
<!DOCTYPE html>
<html>
<head>
<style>
html {
scroll-behavior: smooth;
}
* {
box-sizing: border-box;
}
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
margin: 0px;
padding: 0px;
}
h2 {
text-align: center;
}
#firstSection {
height: 100vh;
background-color: rgb(119, 77, 219);
color: white;
padding: 20px;
}
#secondSection {
height: 100vh;
color: white;
background-color: rgb(42, 128, 168);
padding: 20px;
}
a {
text-decoration: none;
font-size: 20px;
font-weight: bold;
color: yellow;
background-color: black;
}
</style>
</head>
<body>
<h1>Smooth Scroll Example</h1>
<div id="firstSection">
<h2>Top</h2>
<a href="#secondSection">Click Here to Smooth Scroll Below</a>
</div>
<div id="secondSection">
<h2>Bottom</h2>
<a href="#firstSection">Click Me to Smooth Scroll Above</a>
</div>
</body>
</html>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 語言
C++
C#
MongoDB
MySQL
Javascript
PHP