自動輪播到最後一張跳回第一張時,切換動畫明顯比正常間隔(300ms)慢一點。
out_fun = function() {
if (i < listLen) { i++; } else { i = 0; } // 重置索引
$(".btn li").eq(i).addClass("on").siblings().removeClass("on");
$(".pic li").eq(i).animate({opacity:"show"},300).siblings().animate({opacity:"hide"},300);
}
outPlay = function() { setInter = setInterval("out_fun()", speen); }
setInterval("out_fun()", speen) 每次都要 `eval` 解析字符串,有微小開銷。animate({opacity:"show"}) 和 animate({opacity:"hide"}) 並發執行,最後一張 hide 未完成時第一張 show 已排隊,視覺上感覺延遲。i = 0 瞬間觸發,但動畫仍在隊列中。setInter = setInterval(out_fun, speen); // 直接傳函數引用
.pic li { opacity: 0; transition: opacity 0.3s; position: absolute; top:0; left:0; }
.pic li.active { opacity: 1; z-index: 1; }
// 切換只需切換 class
$(".pic li").removeClass("active").eq(i).addClass("active");
GPU 加速、無隊列堵塞、性能極佳。
// 複製第一張到末尾,最後一張到開頭,實現無縫滾動
// 或使用模運算索引,配合 CSS transform translateX 實現真正無縫輪播
var $items = $(".pic li"), $btns = $(".btn li"), len = $items.length, idx = 0, timer;
function slide(to) {
idx = (to + len) % len;
$items.removeClass("active").eq(idx).addClass("active");
$btns.removeClass("on").eq(idx).addClass("on");
}
function auto() { timer = setInterval(function() { slide(idx + 1); }, 3000); }
$btns.click(function() { clearInterval(timer); slide($(this).index()); auto(); });
$items.hover(function() { clearInterval(timer); }, auto);
auto();
核心優化:CSS transition 替代 animate + setInterval 傳函數引用 + 模運算索引。若需更高級效果(無縫、觸控、懶加載),建議直接使用成熟庫 Swiper、Owl Carousel 2。