TL;博士 - 例如:http://jsbin.com/ufoceq/8/
一個簡單的方法來創建一個無限的圖像滑塊沒有太多的努力,如下所示:讓我們說,爲了簡單起見,您有<n>
圖像在循環中滑動,以便在n
th想象的下一張照片是1
st(反之亦然)。
的想法是讓
- 最後一個圖像的克隆的第一個之前被預先計劃建立第一個和最後圖像的克隆;
- 第一張圖片的克隆被追加到最後一張圖片的後面。
無論您的圖片的數量是多少,您至少需要追加2個克隆元素。
再一次爲了簡單起見,假設所有圖像都是100px
寬,並且它們被包裝在一個容器中,您可以左右移動到與overflow: hidden
相關的修剪遮罩中。然後,所有圖像可以很容易地與容器上的display: inline-block
和white-space: nowrap
對齊(現在更容易使用flexbox
)。
對於n = 4
DOM結構是這樣的:
offset(px) 0 100 200 300 400 500
images | 4c | 1 | 2 | 3 | 4 | 1c
/* ^^ ^^
[ Clone of the last image ] [ Clone of the 1st image ]
*/
在開始的時候,您的容器將被定位left: -100px
(或者也margin-left: -100px
or even better (for a matter of performance)transform: translateX(-100px)
),因此滑塊可以顯示第一張圖像。要從一個圖像切換到另一個,您需要在您之前選擇的同一個屬性上應用JavaScript動畫。
當你的滑蓋是目前在4 日形象,你必須從圖像4
切換到1c
,這樣的想法是在動畫結束不久,在真正的重新定位你的滑蓋包裝執行的回調1 st圖像偏移(例如您設置left: -100px
到容器)
這類似於當你滑板目前位於1 ST元素:顯示你只需要從圖像1
執行動畫4c
以前的形象,當動畫已完成您只需移動容器,以便滑塊位於圖像偏移量(例如,將left: -400px
設置爲容器)。
你可以看到上面的小提琴效果:這是最小js/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 });
}
});
}
});
});
正如前面提到的,這種解決方案並不需要真正的精力和談論的性能,而無需循環這種方法比較正常滑塊,它只需要做兩個額外的DOM插入時滑塊初始化一些(相當triv ial)額外的邏輯來管理後向/前向循環。
我不知道是否存在一個更簡單或更好的方法,但希望這有助於反正。
注意:如果您還需要有一個響應畫廊,也許this answer可以幫助過
謝謝您的詳細解釋! – user1828928 2013-04-08 12:08:41
@ user1828928如果您對現場示例感興趣,我創建了一個短小提琴 – fcalderan 2013-04-09 09:11:51
對不起第一個標誌。我認爲電線已經穿過那裏,因爲你對這裏的wiki地位是正確的。 – 2013-04-10 01:19:48