You need to enable JavaScript to run this app. Mac端Firefox浏览器scroll事件监听异常导致滚动驱动视频进度失效问题
优惠活动
大模型
产品
解决方案
定价
更多

Mac端Firefox浏览器scroll事件监听异常导致滚动驱动视频进度失效问题

根因说明

MacOS端Firefox默认对scroll事件回调内的高开销操作(比如媒体时间跳转、DOM重绘)做了节流优化,仅在滚动结束或滚动速度极慢时才会放开限制正常触发回调,这是浏览器自带的性能防护策略,不是代码逻辑错误。

解决方案

  • 抽离视频进度更新逻辑,用requestAnimationFrame独立驱动更新,scroll回调仅负责记录当前滚动百分比,避开Firefox对scroll回调内操作的节流限制
    调整后的参考代码:
    const video = document.getElementById('video');
    const main = document.querySelector('main')
    const viewportHeight = window.outerHeight
    const mainDeets = main.getBoundingClientRect()
    const scrollyHeight = mainDeets.height
    const initialTopOffset = mainDeets.top
    const adjustedHeight = scrollyHeight - initialTopOffset
    let percentScrolled = 0
    let videoDuration = 0
    
    // 独立的视频进度更新逻辑,由raf持续调用
    function syncVideoProgress() {
      if (percentScrolled >= 0 && videoDuration) {
        video.currentTime = videoDuration * percentScrolled
      }
      requestAnimationFrame(syncVideoProgress)
    }
    
    video.onloadedmetadata = () => {
      videoDuration = video.duration
      // 元数据加载完成后启动进度同步循环
      syncVideoProgress()
    }
    
    // scroll回调仅做百分比计算,不直接操作视频
    window.addEventListener('scroll', () => {
      const gbcr = main.getBoundingClientRect()
      percentScrolled = gbcr.top / -adjustedHeight
    }, { passive: true })
    
  • 给scroll事件添加passive: true配置,告知浏览器该滚动回调不会调用preventDefault,能进一步提升滚动事件的响应优先级,降低被节流的概率
  • 可选优化:增加百分比变化阈值判断,仅当滚动百分比变化超过0.2%时才更新视频进度,减少不必要的媒体操作调用,进一步提升流畅度:
    let lastUpdatedPercent = 0
    function syncVideoProgress() {
      const threshold = 0.002 // 对应0.2%的变化阈值
      if (videoDuration && Math.abs(percentScrolled - lastUpdatedPercent) > threshold) {
        lastUpdatedPercent = percentScrolled
        if (percentScrolled >= 0) {
          video.currentTime = videoDuration * percentScrolled
        }
      }
      requestAnimationFrame(syncVideoProgress)
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.08 11:12:00