要实现CSS滚动动画并链接到另一个div
,你可以使用CSS的scroll-behavior
属性和锚点
(anchor)来实现平滑滚动效果。以下是详细步骤和示例代码:
<a>
标签的href
属性指向页面内的某个元素ID,实现页面内跳转。scroll-behavior: smooth;
可以实现平滑滚动效果。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS Scroll Animation</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<nav>
<a href="#section1">Go to Section 1</a>
<a href="#section2">Go to Section 2</a>
</nav>
<div id="section1" class="section">
<h2>Section 1</h2>
<p>This is the content of section 1.</p>
</div>
<div id="section2" class="section">
<h2>Section 2</h2>
<p>This is the content of section 2.</p>
</div>
</body>
</html>
html {
scroll-behavior: smooth; /* 启用平滑滚动 */
}
body {
font-family: Arial, sans-serif;
}
nav {
position: fixed;
top: 0;
width: 100%;
background: #333;
text-align: center;
padding: 10px 0;
}
nav a {
color: white;
margin: 0 15px;
text-decoration: none;
}
.section {
height: 100vh; /* 每个section占满整个视口高度 */
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
color: white;
}
#section1 {
background-color: #4CAF50;
}
#section2 {
background-color: #2196F3;
}
scroll-behavior: smooth;
已正确添加到html
或body
选择器中。div
的ID必须是唯一的。通过以上步骤和代码示例,你应该能够实现一个简单的CSS滚动动画,并链接到页面中的不同div
部分。
没有搜到相关的沙龙
领取专属 10元无门槛券
手把手带您无忧上云