使用 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中文网其他相关文章!