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