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

修复testimonial slider客户评价滑块非预期水平滚动条问题

问题原因

你当前的代码核心问题有2个:

  1. 容器、滑块宽度全部写死为固定像素值,当视口宽度小于800px时,固定宽度的容器会撑出页面水平滚动条
  2. 溢出隐藏的规则没有生效在正确的容器层级,导致超出的评价内容没有被裁剪

修复步骤

1. CSS修改

替换对应CSS规则为以下内容:

/* 可选:全局禁止水平滚动,避免其他元素撑出滚动条 */
body {
  overflow-x: hidden;
}

.testimonial__container {
  max-width: 800px; /* 原来的width改为max-width,限制最大宽度 */
  width: 100%; /* 小屏自动占满可用宽度 */
  height: 400px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  overflow: hidden; /* 容器层直接裁剪超出内容,确保其他评价不可见 */
}

.slide-row {
  display: flex;
  width: 400%; /* 4个滑块总宽度为容器的4倍,替换原来的固定3200px */
  transition: 0.5s;
}

.slide-col {
  width: 100%; /* 单个滑块宽度和容器保持一致,替换原来的固定800px */
  flex-shrink: 0; /* 禁止flex布局自动挤压滑块宽度 */
  height: 400px;
  position: relative;
}

2. JS修改

替换原有JS代码为以下内容,不再写死滑动距离,自动适配容器宽度:

var test__btn = document.getElementsByClassName("test__btn");
var slide = document.getElementById("slide");
// 动态获取当前容器宽度
var containerWidth = document.querySelector('.testimonial__container').offsetWidth;

// 循环绑定点击事件,避免重复代码
for(let i = 0; i < test__btn.length; i++){
  test__btn[i].onclick = function() {
    // 动态计算需要滑动的距离
    slide.style.transform = `translateX(-${i * containerWidth}px)`;
    for (let j = 0; j < test__btn.length; j++) {
      test__btn[j].classList.remove("active");
    }
    this.classList.add("active");
  };
}

// 监听窗口缩放,自动更新滑动距离适配新的容器宽度
window.onresize = function(){
  containerWidth = document.querySelector('.testimonial__container').offsetWidth;
  // 保持当前选中的滑块位置正确
  let activeIndex = Array.from(test__btn).findIndex(btn => btn.classList.contains('active'));
  slide.style.transform = `translateX(-${activeIndex * containerWidth}px)`;
}

效果说明

修改后超出容器的评价会被完全隐藏,点击底部指示器会平滑滑动到对应评价,不会出现非预期的水平滚动条,同时支持不同屏幕尺寸自适应,不会出现评价挤在一起的问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 05:06:02