实现JavaScript自动滚动上下循环及鼠标悬停暂停功能求助
实现循环上下滚动及鼠标悬停暂停效果
以下是满足需求的完整代码实现:
HTML
<div id="div1"> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> This is a DIV<br> </div>
CSS
#div1 { height: 100px; width: 200px; border: 1px solid #ccc; overflow: auto; }
JavaScript
// 获取目标滚动容器 const scrollContainer = $('#div1'); // 滚动方向:1=向下,-1=向上 let scrollDirection = 1; // 定时器实例 let scrollTimer; // 启动滚动的核心函数 function initScroll() { scrollTimer = setInterval(() => { const currentScrollTop = scrollContainer.scrollTop(); // 计算容器可滚动的最大距离(总高度-可视高度) const maxScrollTop = scrollContainer[0].scrollHeight - scrollContainer[0].clientHeight; // 到达底部则切换为向上滚动 if (currentScrollTop >= maxScrollTop) { scrollDirection = -1; } // 到达顶部则切换为向下滚动 else if (currentScrollTop <= 0) { scrollDirection = 1; } // 执行滚动操作 scrollContainer.scrollTop(currentScrollTop + 10 * scrollDirection); }, 100); } // 初始化启动滚动 initScroll(); // 鼠标悬停时暂停滚动 scrollContainer.on('mouseenter', () => { clearInterval(scrollTimer); }); // 鼠标离开时恢复滚动 scrollContainer.on('mouseleave', () => { initScroll(); });
关键改动说明
循环上下滚动:
- 新增
scrollDirection变量控制滚动方向,到达底部/顶部时切换方向 - 修正滚动边界判断逻辑:通过
scrollHeight - clientHeight计算容器可滚动的最大距离,解决原代码边界判断不准确的问题 - 移除原代码中到达底部停止滚动的逻辑,实现持续循环
- 新增
鼠标悬停暂停:
- 给容器绑定
mouseenter事件,触发时清除定时器暂停滚动 - 绑定
mouseleave事件,触发时重新初始化滚动定时器
- 给容器绑定
体验优化:
- 将滚动间隔从1000ms调整为100ms,让滚动更流畅(可根据需求自行修改数值)
- 缓存DOM元素引用,避免重复查询提升性能
内容的提问来源于stack exchange,提问作者mike36
相关产品推荐
相关产品推荐

