JavaScript 滚动切换 div
内容是指通过 JavaScript 监听用户的滚动事件,并根据滚动的距离或方向来动态地显示或隐藏不同的 div
元素。这种技术常用于创建单页应用程序(SPA)中的导航效果,或者在有限的空间内展示大量内容。
以下是一个简单的垂直滚动切换 div
内容的示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Scroll Switch Div Content</title>
<style>
.section {
height: 100vh;
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 = 1;
const sections = document.querySelectorAll('.section');
window.addEventListener('wheel', (event) => {
if (event.deltaY > 0 && currentSection < sections.length) {
currentSection++;
} else if (event.deltaY < 0 && currentSection > 1) {
currentSection--;
}
sections.forEach((section, index) => {
section.style.transform = `translateY(${(index - currentSection + 1) * 100}vh)`;
});
});
</script>
</body>
</html>
问题:滚动切换时页面跳动或卡顿。
原因:可能是由于 JavaScript 执行效率不高,或者 CSS 动画不够平滑。
解决方法:
requestAnimationFrame
来优化动画性能。transform
和 opacity
属性)。示例代码优化:
let currentSection = 1;
const sections = document.querySelectorAll('.section');
function scrollToSection(index) {
sections.forEach((section, i) => {
section.style.transform = `translateY(${(i - index) * 100}vh)`;
});
}
window.addEventListener('wheel', (event) => {
event.preventDefault();
const direction = event.deltaY > 0 ? 1 : -1;
const newIndex = currentSection + direction;
if (newIndex >= 1 && newIndex <= sections.length) {
currentSection = newIndex;
requestAnimationFrame(() => scrollToSection(currentSection));
}
});
通过这种方式,可以确保滚动切换更加流畅和高效。