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>

页面效果如图:

相关推荐
LaughingZhu4 小时前
Product Hunt 每日热榜 | 2026-05-21
前端·人工智能·经验分享·chatgpt·html
怕浪猫4 小时前
Electron 开发实战(一):从零入门核心基础与环境搭建
前端·electron·ai编程
小鹏linux5 小时前
Ubuntu 22.04 部署开源免费具有精美现代web页面的Casdoor账号管理系统
linux·前端·ubuntu·开源·堡垒机
前端若水6 小时前
会话管理:创建、切换、删除对话历史
前端·人工智能·python·react.js
Bigger6 小时前
mini-cc:一个轻量级 AI 编程助手的诞生
前端·ai编程·claude
涵涵(互关)6 小时前
Naive-ui树型选择器只显示根节点
前端·ui·vue
BY组态7 小时前
Ricon组态系统最佳实践:从零开始构建物联网监控平台
前端·物联网·iot·web组态·组态
BY组态7 小时前
Ricon组态系统vs传统组态软件:为什么选择新一代Web组态平台
前端·物联网·iot·web组态·组态
SoaringHeart7 小时前
Flutter进阶:OverlayEntry 插入图层管理器 NOverlayZIndexManager
前端·flutter
放下华子我只抽RuiKe57 小时前
React 从入门到生产(四):自定义 Hook
前端·javascript·人工智能·深度学习·react.js·自然语言处理·前端框架