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

如何实现Showit平台网页的横向滚动而非纵向滚动?

解决Showit网页横向滚动的实现方案

现有代码的核心问题

  • CSS选择器使用错误:.d .sib-canvas-1 .sib-canvas-2 .sib-canvas-3 .ss-bg是后代选择器,无法选中并列的画布容器;
  • JS硬编码数值totalWidth - 2500导致宽度计算不准确,且存在重复逻辑;
  • 未监听窗口尺寸变化,无法在屏幕切换时自动适配;
  • 滚动事件绑定逻辑有误,滚轮横向滚动不生效。

修正后的CSS代码

<style>
  /* 全局禁用纵向滚动,开启横向滚动 */
  body, html {
    overflow-y: hidden;
    overflow-x: auto;
    margin: 0;
    padding: 0;
    height: 100vh;
  }

  /* Showit页面容器设置横向弹性布局 */
  .sp {
    display: flex;
    flex-wrap: nowrap;
    height: 100vh;
    width: auto !important;
  }

  /* 每个画布容器占满视口高度,宽度固定为100vw */
  .sb {
    flex: 0 0 100vw;
    height: 100vh;
    min-width: 100vw;
  }

  /* 移动端恢复纵向滚动逻辑 */
  @media (max-width: 699px) {
    body, html {
      overflow-y: auto;
      overflow-x: hidden;
    }
    .sp {
      flex-wrap: wrap;
      width: 100% !important;
    }
    .sb {
      flex: 0 0 100%;
      min-width: 100%;
    }
  }
</style>

修正后的JavaScript代码

// 封装横向滚动逻辑为复用函数
function setupHorizontalScroll() {
  const mediaQuery = window.matchMedia('(min-width: 700px)');
  const pageContainer = document.querySelector('.sp');
  const sectionContainers = document.querySelectorAll('.sb');

  if (!pageContainer || sectionContainers.length === 0) return;

  if (mediaQuery.matches) {
    // 动态计算所有画布的总宽度
    let totalWidth = 0;
    sectionContainers.forEach(section => {
      totalWidth += section.offsetWidth;
    });
    pageContainer.style.width = `${totalWidth}px`;

    // 滚轮事件处理:转为横向滚动
    const handleWheel = (evt) => {
      evt.preventDefault();
      pageContainer.scrollBy({
        left: evt.deltaY * 1.5,
        behavior: 'smooth'
      });
    };

    // 避免重复绑定事件
    pageContainer.removeEventListener('wheel', handleWheel);
    pageContainer.addEventListener('wheel', handleWheel);

    document.documentElement.style.overflowX = 'hidden';
  } else {
    // 移动端恢复默认布局
    pageContainer.style.width = '100%';
    document.documentElement.style.overflowX = 'auto';
  }
}

// 页面加载与窗口尺寸变化时触发逻辑
window.addEventListener('load', setupHorizontalScroll);
window.addEventListener('resize', setupHorizontalScroll);

关键适配说明

  1. CSS优化:用Flexbox实现横向布局,替代white-space: nowrap,兼容性更强;通过媒体查询自动适配移动端纵向滚动。
  2. JS逻辑优化:
    • 移除硬编码数值,动态计算画布总宽度;
    • 监听窗口resize事件,保证屏幕尺寸变化时布局自动调整;
    • 直接在页面容器上绑定滚动事件,实现精准横向滚动,添加平滑滚动效果;
    • 先移除旧事件再绑定,避免重复触发导致的滚动异常。
  3. Showit特殊适配:确认.sp为页面根容器、.sb为画布容器类(根据你的预览页面DOM结构确认),若Showit更新类名需同步调整选择器。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.29 10:52:30