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>

页面效果如图:

相关推荐
前端付豪2 分钟前
实现必要的流式输出(Streaming)
前端·后端·agent
张元清5 分钟前
useMediaQuery:React 响应式设计完全指南
前端·javascript·面试
小金鱼Y5 分钟前
一文吃透 JavaScript 防抖:从原理到实战,让你的页面不再 “手抖”
前端·javascript·面试
Z兽兽8 分钟前
React 18 开发环境下useEffect 会执行两次,原因分析及解决方案
前端·react.js·前端框架
紫_龙10 分钟前
最新版vue3+TypeScript开发入门到实战教程之Vue3详解props
前端·vue.js·typescript
树上有只程序猿17 分钟前
这波低代码热,能维持多久
前端
姓王名礼22 分钟前
这是一个完整的全栈交付包,包含Vue3 前端交互界面(集成数字人视频流、ECharts 图表、语音对话)和Docker Compose 一键部署脚本。
前端·docker·echarts
嵌入式-老费26 分钟前
vivado hls的应用(axis接口)
前端·webpack·node.js
孟陬33 分钟前
国外技术周刊第 2 期 — 本周热门 🔥 YouTube 视频 TED 演讲 AI 如何能够拯救(而非摧毁)教育
前端·后端·程序员
小飞大王6661 小时前
从零手写 React:深度解析 Fiber 架构与 Hooks 实现
前端·react.js·架构