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

jQuery轮播如何使用自定义变量作为scrollLeft滚动偏移值

代码错误原因
  • 变量调用错误:你已通过$('.userProfileCarousel').width()将宽度数值赋值给carouselWidth变量,后续直接调用变量即可,原代码写的carouselWidth()是把普通变量当作函数执行,会直接抛出语法错误。
  • DOM选择器逻辑错误:carouselPrev、carouselNext本身就是.userProfileCarousel的直接子元素,调用$(this).parent()获取到的就是需要滚动的轮播容器本身,原代码的parent().find('.userProfileCarousel')、next('.userProfileCarousel')均无法匹配到目标元素,滚动逻辑不会触发。
  • 语法格式错误:jQuery animate的相对数值赋值需要将+=/-=和数值拼接为字符串,原代码未加引号包裹,属于语法错误。
  • 额外优化点:原代码在页面初始化时就获取轮播宽度,若用户缩放窗口会导致宽度取值不准,建议改为点击按钮时实时获取宽度。
修正后可运行的jQuery代码
$(function() {
  $('.carouselPrev').click(function(event) {
    event.preventDefault();
    const carouselWidth = $(this).parent().width();
    $(this).parent().animate({
      scrollLeft: `-=${carouselWidth}`
    }, "slow");
  });
  $('.carouselNext').click(function(event) {
    event.preventDefault();
    const carouselWidth = $(this).parent().width();
    $(this).parent().animate({
      scrollLeft: `+=${carouselWidth}`
    }, "slow");
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.07 14:57:00