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

JavaScript轮播图(carousel slider)点击右按钮无法切换第三张报错求助

问题原因

两个报错均来自JS逻辑的基础错误:

  • cannot read properties of undefined (reading "add"):你在获取nextSlide时直接调用了getBoundingClientRect(),该方法返回的是仅包含尺寸、位置属性的普通对象,不是DOM元素本身,不存在classList属性,调用add方法自然失败。
  • Cannot read properties of null (reading "nextElementSibling"):一是没有做边界校验,当当前激活的幻灯片是最后一张时,nextElementSibling会返回null,调用属性直接报错;二是位移逻辑错误,每次仅移动单张幻灯片宽度,没有累计位移值,就算解决第一个问题也无法正常滑动到第三张。

另外原代码还有两处隐性问题:slideWidth存的是完整DOMRect对象,给幻灯片设置left值时运算逻辑错误;位移写死为单张宽度,滑动到第二张后再点击永远只能停在第二张的位置。

修复方案

以下是修复后的完整JS代码,核心修改点包括:拆分DOM元素和尺寸的获取、新增激活索引计算累计位移、增加边界判断、修正宽度取值逻辑:

// CAROUSEL
const carousel = document.querySelector(".cards-wrapper");
const slides = [...carousel.children];
const nextButton = document.querySelector(".button-right");
const previousButton = document.querySelector(".button-left");

// 仅取幻灯片宽度数值
let slideWidth = slides[0].getBoundingClientRect().width;
// 记录当前激活的幻灯片索引
let activeIndex = 0;

function positionSlides(slides) {
  for (let index = 0; index < slides.length; index++) {
    slides[index].style.left = slideWidth * index + "px";
  }
}

positionSlides(slides);

nextButton.addEventListener("click", () => {
  const currentSlide = carousel.querySelector(".active");
  // 先拿真实的下一张DOM元素
  let nextSlide = currentSlide.nextElementSibling;
  // 边界判断:如果是最后一张,下一张跳回第一张,不需要该逻辑可替换为按钮禁用逻辑
  if (!nextSlide) {
    nextSlide = slides[0];
    activeIndex = 0;
  } else {
    activeIndex++;
  }
  
  // 计算累计位移
  const position = slideWidth * activeIndex;
  carousel.style.transform = `translateX(-${position}px)`;

  currentSlide.classList.remove("active");
  nextSlide.classList.add("active");
});

内容的提问来源于stack exchange,提问作者Jorik van Ruiswijk

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 08:06:04