html 实现鼠标滑动点亮横轴

实现一个有多个节点的横轴,鼠标向下滑动从左到右点亮横轴,鼠标向上滑动从右到左取消点亮效果。

代码:

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>

页面效果如图:

相关推荐
捡田螺的小男孩19 小时前
什么是 Skill?手把手带你写一个简单有用的 Skill!
前端·后端·程序员
IT_陈寒19 小时前
Redis集群这个坑,差点让我通宵
前端·人工智能·后端
90后的晨仔19 小时前
uni-app 路由跳转与页面导航 —— 终极详解(对标 iOS / Android / 鸿蒙三端原生)
前端
Heo20 小时前
大厂前端调试不能只会debugger
前端·javascript·面试
用户21816970493020 小时前
Flutter (十七) 网络请求
前端
cidy_9820 小时前
React 19 + Vite 企业级前端项目:从零搭建到规范交付
前端
用户9210802628620 小时前
如何把一张图片做成自定义复杂 UI 图标
前端
用户9385156350720 小时前
从 0 拆解一个 Next.js 笔记系统:npx、App Router、RSC 与组件规划全记录
前端·后端·全栈
hello930721 小时前
plop代码生成器
前端
windliang21 小时前
Claude Code 源码分析(十二):错误处理与自动恢复:让 Agent 稳定运行
前端·javascript·面试