如何使用 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