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

全局滚动控制溢出div图片位移时moveImageCalc报NaN错误求解

问题解决

1 NaN报错原因

  • 变量拼写错误:代码中声明的容器高度数组为containerHeightArray,但计算moveImageCalc时误写为conteinerHeigth[index],错误的拼写导致取值为undefined,参与数值运算后直接返回NaN
  • 额外逻辑问题:moveImageCalc是在.container遍历循环内定义的局部变量,后续全局scroll事件中无法正常访问该变量,且该值为静态计算结果,无法匹配滚动的动态偏移需求

2 修复方案

CSS调整

首先隐藏不需要的div滚动条,修改.col2配置:

.col2 {
  flex: 1;
  height: 200px;
  overflow: hidden; /* 替换原来的scroll,直接隐藏溢出和滚动条 */
  position: relative;
}

完整JS代码

// 等待图片加载完成再计算尺寸,避免获取到高度为0
$(window).on('load', function() {
  const viewportHeight = window.innerHeight;
  
  $(window).on('scroll', function() {
    const scrollTop = $(window).scrollTop();
    
    $('.container').each(function() {
      const $col2 = $(this).find('.col2');
      const $img = $col2.find('img');
      const col2Height = $col2.height();
      const imgHeight = $img.height();
      // 图片高度小于容器高度不需要滚动
      if (imgHeight <= col2Height) return;
      
      const rect = $col2[0].getBoundingClientRect();
      // 容器不在视口内跳过
      if (rect.bottom < 0 || rect.top > viewportHeight) return;
      
      // 计算滚动进度:容器进入视口的比例
      const scrollPercent = (viewportHeight - rect.top) / (viewportHeight + col2Height);
      // 计算图片可滚动的总距离
      const scrollableDistance = imgHeight - col2Height;
      // 计算当前图片偏移量,限制在0到负的可滚动距离之间
      const imgOffset = -Math.max(0, Math.min(scrollableDistance, scrollPercent * scrollableDistance));
      
      $img.css('top', imgOffset + 'px');
    });
  });
  
  // 初始化触发一次滚动计算
  $(window).trigger('scroll');
})

说明

  • 新增图片加载完成的监听,避免图片未加载完获取高度为0的问题
  • 移除了冗余的数组存储逻辑,直接遍历DOM节点实时计算,逻辑更简洁不易出错
  • 滚动进度计算适配了容器进入视口的比例,实现图片滚动和页面滚动同步的效果
  • 不需要额外的视口判断和requestAnimationFrame循环,滚动事件本身触发频率足够满足需求

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 05:24:03