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

多Section横向自动滚动异常:window.innerWidth无变化但函数触发

问题修复:容器内Section自动横向滚动异常

核心问题分析

  1. 滚动目标错误:你现在给services-wrapper设置scrollLeft,但它的宽度和内部三个section的总宽度完全一致(300vw),内容没有超出容器,所以滚动值不会有变化。应该让services-wrapper的父容器作为可滚动容器,动画目标改为父容器的scrollLeft。
  2. 初始滚动逻辑无效:第一次调用autoScroll时,currentIndex为0,滚动到0 * window.innerWidth等于没动,导致首次执行无效果。
  3. 未适配窗口大小变化:window.innerWidth只会在初始化时获取一次,窗口缩放后,滚动距离会和实际section宽度不匹配。

修复步骤

1. 调整HTML结构,添加外层滚动容器

给services-wrapper套一个外层容器,用来承载滚动逻辑:

<div class="services-container">
  <div class="services-wrapper">
    <!-- 原有的三个section代码保持不变 -->
  </div>
</div>

2. 更新CSS样式

body,
html {
  margin: 0;
  padding: 0;
  overflow-x: hidden;
}

/* 新增外层容器,作为可滚动载体 */
.services-container {
  width: 100vw;
  height: 100vh;
  overflow-x: hidden; /* 隐藏滚动条,保持视觉整洁 */
  position: relative;
}

.services-wrapper {
  display: flex;
  width: 300vw;
  height: 100vh;
}

.services-section {
  width: 100vw;
  height: 100vh;
  overflow-x: hidden;
}

3. 修正JavaScript逻辑

jQuery(document).ready(function($) {
  let currentIndex = 0;
  const totalSections = $('.services-section').length;
  const scrollInterval = 5000;
  let viewportWidth = window.innerWidth;

  // 监听窗口缩放,实时更新视口宽度并修正滚动位置
  $(window).on('resize', function() {
    viewportWidth = window.innerWidth;
    $('.services-container').scrollLeft(currentIndex * viewportWidth);
  });

  function autoScroll() {
    // 先更新索引,再执行滚动,确保第一次就有效果
    currentIndex++;
    if (currentIndex >= totalSections) {
      currentIndex = 0;
    }

    console.log('Current Index:', currentIndex);
    console.log('Window Width:', viewportWidth);

    $('.services-container').animate({
      scrollLeft: currentIndex * viewportWidth
    }, 800);
  }

  // 页面加载后先停留初始状态,再开始自动滚动
  setTimeout(function() {
    setInterval(autoScroll, scrollInterval);
  }, scrollInterval);
});

补充说明

  • window.innerWidth数值不变是正常的,它仅反映当前窗口视口宽度,只有窗口大小变化时才会改变,所以需要通过resize事件监听更新。
  • 如果需要显示横向滚动条,把.services-container的overflow-x:hidden改为overflow-x:auto即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 02:00:54