以下是一个使用JavaScript实现全屏滚动的简单示例代码:
HTML结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>全屏滚动示例</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<section class="section">第一屏内容</section>
<section class="section">第二屏内容</section>
<section class="section">第三屏内容</section>
<script src="script.js"></script>
</body>
</html>
CSS样式(styles.css)
html, body {
margin: 0;
padding: 0;
height: 100%;
overflow: hidden;
}
.section {
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
font-size: 2em;
}
.section:nth - child(1) {
background-color: lightblue;
}
.section:nth - child(2) {
background-color: lightgreen;
}
.section:nth - child(3) {
background-color: lightcoral;
}
JavaScript代码(script.js)
let currentSection = 0;
const sections = document.querySelectorAll('.section');
const totalSections = sections.length;
window.addEventListener('wheel', function (e) {
if (e.deltaY > 0) {
// 向下滚动
currentSection++;
if (currentSection >= totalSections) {
currentSection = totalSections - 1;
}
} else {
// 向上滚动
currentSection--;
if (currentSection < 0) {
currentSection = 0;
}
}
scrollToSection(currentSection);
});
function scrollToSection(index) {
sections[index].scrollIntoView({
behavior: 'smooth'
});
}
基础概念
section
元素)进行滚动,并且每次滚动一个完整的屏幕高度或者宽度(取决于布局方向),给用户一种简洁、有节奏感的浏览体验。优势
应用场景
如果在实现过程中遇到问题,例如滚动不流畅:
scrollIntoView
方法的支持程度可能有所不同。scroll-behavior: smooth
属性,一些旧版本浏览器可能不支持,可以使用JavaScript动画库(如GSAP)来实现更平滑的滚动效果。如果遇到内容没有正确对齐全屏的情况:
vh
、vw
)时出现偏差,或者容器元素存在默认的边距、填充等影响布局。margin
和padding
)设置为合适的值(通常是0)。领取专属 10元无门槛券
手把手带您无忧上云