You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.18 13:33:10