全屏滚动(FullPage Scroll)是一种网页设计技术,它允许用户通过滚动页面来导航不同的内容区域。横向全屏滚动是指页面在水平方向上滚动,而纵向全屏滚动则是在垂直方向上滚动。
以下是一个简单的JavaScript实现纵向全屏滚动的示例代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>FullPage Scroll</title>
<style>
body, html {
margin: 0;
padding: 0;
overflow: hidden;
}
.section {
height: 100vh;
width: 100%;
display: flex;
align-items: center;
justify-content: center;
font-size: 2em;
color: white;
}
#section1 { background-color: #3498db; }
#section2 { background-color: #2ecc71; }
#section3 { background-color: #e74c3c; }
</style>
</head>
<body>
<div id="section1" class="section">Section 1</div>
<div id="section2" class="section">Section 2</div>
<div id="section3" class="section">Section 3</div>
<script>
let currentSection = 0;
const sections = document.querySelectorAll('.section');
function scrollToSection(index) {
sections[index].scrollIntoView({ behavior: 'smooth' });
currentSection = index;
}
window.addEventListener('wheel', (event) => {
if (event.deltaY > 0 && currentSection < sections.length - 1) {
scrollToSection(currentSection + 1);
} else if (event.deltaY < 0 && currentSection > 0) {
scrollToSection(currentSection - 1);
}
});
</script>
</body>
</html>
原因:
解决方法:
function scrollToSection(index) {
sections[index].scrollIntoView({ behavior: 'smooth' });
currentSection = index;
}
let rafId;
window.addEventListener('wheel', (event) => {
if (rafId) cancelAnimationFrame(rafId);
rafId = requestAnimationFrame(() => {
if (event.deltaY > 0 && currentSection < sections.length - 1) {
scrollToSection(currentSection + 1);
} else if (event.deltaY < 0 && currentSection > 0) {
scrollToSection(currentSection - 1);
}
});
});
通过以上方法,可以有效提升全屏滚动的流畅性和用户体验。
领取专属 10元无门槛券
手把手带您无忧上云