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
相关产品推荐
相关产品推荐

