实现一个有多个节点的横轴,鼠标向下滑动从左到右点亮横轴,鼠标向上滑动从右到左取消点亮效果。
代码:
html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Timeline Scroll Effect</title>
<style>
.timeline {
position: relative;
height: 4px;
background-color: #e0e0e0; /* 横轴"未点亮"的颜色 */
margin: 40px 0;
}
.timeline-progress {
position: absolute;
top: 0;
left: 0;
height: 100%;
background-color: #00bcd4; /* 横轴"点亮"的颜色 */
width: 0;
transition: width 0.1s ease; /* 宽度变化的平滑过渡 */
}
.timeline-dot {
position: absolute;
top: 50%;
transform: translateY(-50%); /* 垂直居中 */
width: 12px;
height: 12px;
border-radius: 50%; /* 圆形 */
background-color: #e0e0e0; /* 节点"未点亮"颜色 */
transition: background-color 0.2s ease; /* 节点颜色过渡 */
}
</style>
</head>
<body>
<div class="timeline">
<!-- 进度条:随滚动动态变化宽度 -->
<div class="timeline-progress"></div>
<!-- 横轴上的节点(圆点),通过left定位 -->
<div class="timeline-dot" style="left: 15%;"></div>
<div class="timeline-dot" style="left: 35%;"></div>
<div class="timeline-dot" style="left: 55%;"></div>
<div class="timeline-dot" style="left: 80%;"></div>
</div>
<script>
const timelineProgress = document.querySelector('.timeline-progress');
const timelineDots = document.querySelectorAll('.timeline-dot');
let currentWidth = 0; // 当前点亮的宽度(百分比)
const maxWidth = 100; // 最大宽度(100%)
window.addEventListener('wheel', (e) => {
// deltaY > 0 → 鼠标下滑;deltaY < 0 → 鼠标上滑
const isScrollDown = e.deltaY > 0;
const step = isScrollDown ? 2 : -2; // 每次滚动的"增量/减量"
// 限制宽度在 0 ~ 100 之间
currentWidth = Math.max(0, Math.min(maxWidth, currentWidth + step));
timelineProgress.style.width = `${currentWidth}%`;
// 同步更新节点的点亮状态:进度超过节点位置时,节点点亮
timelineDots.forEach(dot => {
const dotPosition = parseFloat(dot.style.left); // 节点的位置(百分比)
dot.style.backgroundColor =
currentWidth >= dotPosition ? '#00bcd4' : '#e0e0e0';
});
});
</script>
</body>
</html>
页面效果如图: