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>