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

如何使用JavaScript实现鼠标向下滚动时执行函数显示加载屏

实现方案

核心逻辑

  • 监听滚动容器的滚动事件,通过对比当前滚动位置与上一次记录的滚动位置判断滚动方向,仅向下滚动时执行目标函数
  • 新增状态锁避免滚动过程中函数被重复触发

修改后代码

JavaScript

// 存储上一次滚动位置
let lastScrollTop = 0
// 加载状态锁,避免重复触发加载逻辑
let isLoading = false
const scrollContainer = document.querySelector('.demo')
const loadEl = document.querySelector('.load')

function showLoading() {
  // 加载中直接返回,不重复执行
  if (isLoading) return
  isLoading = true
  loadEl.style.display = 'block'

  // 这里可替换为实际的接口请求等逻辑,示例2秒后模拟加载完成
  setTimeout(() => {
    loadEl.style.display = 'none'
    isLoading = false
  }, 2000)
}

scrollContainer.addEventListener('scroll', () => {
  const currentScrollTop = scrollContainer.scrollTop
  // 仅向下滚动时触发逻辑
  if (currentScrollTop > lastScrollTop) {
    // 如果需要滚动到接近底部才触发,可补充下方判断条件
    // if (currentScrollTop + scrollContainer.clientHeight >= scrollContainer.scrollHeight - 50)
    showLoading()
  }
  // 更新上一次滚动位置
  lastScrollTop = currentScrollTop
})

CSS(原有代码无需修改,保留即可

.demo{
  width: 200px;
  height: 300px;
  overflow-y:scroll;
  background-color: #fff;
}


.item{
  list-style:none;
  padding:20px;
  border:1px solid #ccc;
}

.load{
  width:100%;
  margin: 0 auto;
  display: none;
}

HTML(原有代码无需修改,保留即可)

<ul class="demo">
    <li   class="item">article1</li>
    <li  class="item">article2</li>
    <li  class="item">article3</li>
    <li  class="item">article4</li>
    <li  class="item">article5</li>
    <li  class="item">article6</li>
    <li  class="item">article7</li>
    <li  class="item">article8</li>
    <li  class="item">article9</li>
    <li  class="item">article10</li>
<!--  load -->
   <svg class="load" version="1.1" id="loader-1"  x="0px" y="0px"
        width="40px" height="40px" viewBox="0 0 50 50" style="enable-background:new 0 0 50 50;" xml:space="preserve">
    <path fill="#000" d="M43.935,25.145c0-10.318-8.364-18.683-18.683-18.683c-10.318,0-18.683,8.365-18.683,18.683h4.068c0-8.071,6.543-14.615,14.615-14.615c8.072,0,14.615,6.543,14.615,14.615H43.935z">
        <animateTransform attributeType="xml"
        attributeName="transform"
        type="rotate"
        from="0 25 25"
        to="360 25 25"
        dur="0.6s"
        repeatCount="indefinite"/>
    </path>
  </svg>
</ul>

内容的提问来源于stack exchange,提问作者WEI A

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 08:30:04