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">
<style>
body,
html {
margin: 0;
padding: 0;
overflow: hidden;
}
#scrollContainer {
width: 100%;
height: 100vh;
overflow: hidden;
position: relative;
}
#scrollContent {
display: flex;
flex-direction: column;
transition: transform 0.3s ease;
}
.item {
width: 100%;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
font-size: 5em;
color: white;
}
.item:nth-child(odd) {
background-color: #333;
}
.item:nth-child(even) {
background-color: #666;
}
</style>
</head>
<body>
<div id="scrollContainer">
<div id="scrollContent">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
</div>
</div>
</body>
<script>
const scrollContainer = document.getElementById('scrollContainer');
const scrollContent = document.getElementById('scrollContent');
let currentPosition = 0;
let intervalId = null;
const scrollDistance = 2;
const itemHeight = scrollContent.clientHeight / scrollContent.children.length;
const maxScrollPosition = 0;
const minScrollPosition = -itemHeight * (scrollContent.children.length - 1);
function autoScroll() {
if (currentPosition <= minScrollPosition) {
currentPosition = 0;
}
scrollContent.style.transform = `translateY(${currentPosition}px)`;
currentPosition -= scrollDistance;
}
function startAutoScroll() {
intervalId = setInterval(autoScroll, 20);
}
function stopAutoScroll() {
clearInterval(intervalId);
}
function handleWheel(event) {
currentPosition -= event.deltaY;
if (currentPosition > maxScrollPosition) {
currentPosition = maxScrollPosition;
} else if (currentPosition < minScrollPosition) {
currentPosition = minScrollPosition;
}
scrollContent.style.transform = `translateY(${currentPosition}px)`;
}
scrollContainer.addEventListener('mouseenter', function () {
stopAutoScroll();
scrollContainer.addEventListener('wheel', handleWheel);
});
scrollContainer.addEventListener('mouseleave', function () {
scrollContainer.removeEventListener('wheel', handleWheel);
startAutoScroll();
});
startAutoScroll();
</script>
</html>
- 初始化变量(
currentPosition
、intervalId
、scrollDistance
、itemHeight
、maxScrollPosition
、minScrollPosition
),用于跟踪滚动状态和动画。 autoScroll()
函数持续地将scrollContent
向上移动(translateY
),直到达到minScrollPosition
,然后重置。startAutoScroll()
和stopAutoScroll()
函数通过setInterval
和clearInterval
控制自动滚动动画。handleWheel(event)
函数根据鼠标滚轮事件(wheel
)调整currentPosition
,确保滚动保持在maxScrollPosition
和minScrollPosition
定义的范围内。scrollContainer
上的事件监听器(mouseenter
、mouseleave
)触发自动滚动停止/开始,并启用/禁用通过鼠标滚轮进行手动滚动。- 在
mouseenter
时,自动滚动停止,并且可以通过鼠标滚轮进行手动滚动。 - 在
mouseleave
时,手动滚动停止,并且自动滚动恢复。 #scrollContent
中的每个项目占满视口高度,页面可以通过自动或手动方式平滑滚动这些项目。