use*_*928 26 html javascript css jquery
我想知道使用JavaScript/jQuery为网站构建Infinity-Image-Loop-Slider的最佳(良好的可读代码,害虫练习代码,可重用性)概念是什么?我不知道如何编写幻灯片的代码,但是什么蓝图符合上面提到的要求.我的问题的主要焦点是如何安排图片以获得无限循环滑块的印象.
通过查看来自不同Sliders的Code,我遇到了两个解决方案:
- 每次显示下一个/上一个图像时,更改所有图像的z-Index.
- 改变图像在DOM中的位置.
但是检查和理解他人的代码是非常耗时的 - 这就是我问这个问题的原因:-)
fca*_*ran 59
tl; dr - 示例:http://jsbin.com/ufoceq/8/
一个简单的方法没有太多的精力来创建一个无限的图像滑块如下:假设为简单起见,你有<n>
图片在一个循环中滑动,从而使后n
日图像的下一个可视化是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 ]
*/
Run Code Online (Sandbox Code Playgroud)
开始时,您的容器将定位left: -100px
(或者margin-left: -100px
甚至更好(为了性能) transform: translateX(-100px)
),因此滑块可以显示第一个图像.要从图像切换到另一个图像,您需要在之前选择的同一属性上应用javascript动画.
当你的滑块是目前在4 个图像,必须切换从图像4
到1c
,这样的想法是在动画结束不久,在真正的1个重新定位你的滑盖包装执行的回调ST图像偏移量(例如你设置left: -100px
到容器)
这是类似的,当你的滑块当前位于1个ST元素:显示你只需要从图像进行动画上一个图像1
到4c
当动画完成后,您只需移动容器,这样滑块istantly位于4 个图像偏移(例如,你设置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 });
}
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
如前所述,这个解决方案不需要太多努力和谈论性能,将这种方法与普通滑块进行比较而不进行循环,它只需要在初始化滑块时进行两次额外的DOM插入以及一些(非常简单的)额外逻辑管理后退/前进循环.
我不知道是否存在更简单或更好的方法,但希望无论如何这都有帮助.
注意:如果您还需要一个响应式图库,也许这个答案也可能有所帮助