基于jQuery实现自定义轮播图首尾位置隐藏前后导航按钮咨询
自定义滑块导航按钮显隐控制方案
- 新增按钮显隐控制函数,实时计算滑块当前位置与边界阈值的关系
- 分别在初始化、窗口大小调整、滑动动画结束三个时机触发显隐判断,保证不同场景下按钮状态都正确
- 保留原有
.carousel__item { width: auto; height: auto; }的特殊设置无需修改
修改后的完整代码如下:
var $carousel = $(this), $carouselContainer = $carousel.find(".js-carousel-container"), $carouselList = $carousel.find(".js-carousel-list"), $carouselItem = $carousel.find(".js-carousel-item"), $carouselButton = $carousel.find(".js-carousel-button"), // 分别获取前后按钮的jQuery对象 $prevBtn = $carouselButton.filter('[data-dir="prev"]'), $nextBtn = $carouselButton.filter('[data-dir="next"]'), setItemWidth = function(){ $carouselList.removeAttr("style"); var curWidth = $($carouselItem[0]).outerWidth() * $carouselItem.length; $carouselList.css("width", curWidth); }, // 新增:控制导航按钮显隐的函数 toggleNavButtons = function() { var curPos = parseInt($carouselList.css("left")) || 0, containerWidth = $carouselContainer.outerWidth(), listWidth = $carouselList.outerWidth(), // 计算最大可滑动的偏移量(绝对值) maxScrollOffset = listWidth - containerWidth; // 滑块处于起始位置,隐藏上一页按钮 if (curPos >= 0) { $prevBtn.hide(); // 若需要禁用而非隐藏,可替换为:$prevBtn.addClass('is-disabled').prop('disabled', true) } else { $prevBtn.show(); // $prevBtn.removeClass('is-disabled').prop('disabled', false) } // 滑块滑到最后一项,隐藏下一页按钮 if (Math.abs(curPos) >= maxScrollOffset) { $nextBtn.hide(); } else { $nextBtn.show(); } }, slide = function(){ var $button = $(this), dir = $button.data("dir"), curPos = parseInt($carouselList.css("left")) || 0, moveto = 0, containerWidth = $carouselContainer.outerWidth(), listWidth = $carouselList.outerWidth(), before = (curPos + containerWidth), after = listWidth + (curPos - containerWidth); if(dir=="next"){ moveto = (after < containerWidth) ? curPos - after : curPos - containerWidth; } else { moveto = (before >= 0) ? 0 : curPos + containerWidth; } $carouselList.animate({ left: moveto }, { // 动画结束后更新按钮状态 complete: toggleNavButtons }); }; $(window).resize(function(){ setItemWidth(); // 窗口大小变化后重新判断按钮状态 toggleNavButtons(); }); setItemWidth(); // 初始化时先判断一次按钮状态 toggleNavButtons(); $carouselButton.on("click", slide); });
如果需要使用禁用样式而非直接隐藏按钮,可补充以下CSS:
.js-carousel-button.is-disabled { opacity: 0.3; pointer-events: none; cursor: default; }
内容的提问来源于stack exchange,提问作者Urget
相关产品推荐
相关产品推荐

