使用 JavaScript/jQuery的無限循環滑桿設計概念
要建立具有最佳程式碼可讀性、可維護性和可重複使用性的無限循環影像滑桿,請考慮以下藍圖:
無限循環效果的圖像排列
要實現無限循環的幻覺,請實現以下兩種方法之一:
複製影像以實現無縫循環
要建立無限循環,請克隆第一個和最後一個影像在序列中。然後,在滾動時:
範例程式碼
將下列 JavaScript/jQuery 程式碼片段視為範例實作:
$(function() { var gallery = $('#gallery ul'), items = gallery.find('li'), len = items.length, current = 1, /* the item we're currently looking */ first = items.filter(':first'), last = items.filter(':last'), triggers = $('button'); /* 1. Cloning first and last item */ first.before(last.clone(true)); last.after(first.clone(true)); /* 2. Set button handlers */ triggers.on('click', function() { var cycle, delta; if (gallery.is(':not(:animated)')) { cycle = false; delta = (this.id === "prev")? -1 : 1; /* in the example buttons have id "prev" or "next" */ gallery.animate({ left: "+=" + (-100 * delta) }, function() { current += delta; /** * we're cycling the slider when the the value of "current" * variable (after increment/decrement) is 0 or when it exceeds * the initial gallery length */ cycle = (current === 0 || current > len); if (cycle) { /* we switched from image 1 to 4-cloned or from image 4 to 1-cloned */ current = (current === 0)? len : 1; gallery.css({left: -100 * current }); } }); } }); });
以上是如何使用 JavaScript/jQuery 實現無縫無限循環圖像滑桿?的詳細內容。更多資訊請關注PHP中文網其他相關文章!