这是使用before 事件和事件传递的options 属性可用的addSlide() 方法的解决方案。我在代码中添加了 cmets 来解释发生了什么。
代码(小提琴演示:http://jsfiddle.net/QZu2Z/4/)
var pos = 0;
var count = 1;
var maxItems = 7;
var items = [];
function createSlide()
{
// This function takes the array of items we have and builds a new ul
// list based on maxitems and last pos, the result is multiple calls
// to this function produces output like so:
// First pass returns: 1 2 3 4 5 6 7
// Second pass returns: 8 9 1 2 3 4 5
// Third pass returns: 6 7 8 9 1 2 3
// Forth pass returns: 4 5 6 7 8 9 1
// and so forth...
var elem = $('<ul class="list"></ul>');
for(i = 1; i <=9; i++)
{
if (pos >= 9)
{
pos = 0;
}
if(count <= maxItems)
{
count = count + 1;
$(elem).append(items[pos]);
pos = pos + 1;
}
}
count = 1;
return elem;
}
function onBefore(curr, next, opts) {
// This is the onBefore slide event; we're simply checking if the addSlide
// method is available on the opts object as apparently on the first pass,
// addSlide is undefined (plugin hasn't yet created the function);
if (!opts.addSlide)
{
return;
}
// addSlide function is available so generate the next slide and add it
opts.addSlide(createSlide());
}
$(document).ready(function() {
// Generate an array of items to use in our cycle
$(".wrapper li").each(function(i) {
items[i] = $(this).clone().wrap('<div>').parent().html();
});
// Grab the slideshow object
var $ss = $('.wrapper');
// Erase the contents, we have the data stored in the array [items]
$ss.empty();
// Create new slide and append it to our object, results in 1 2 3 4 5 6 7
$ss.append(createSlide());
// Create another slide and append it to our object, results 8 9 1 2 3 4 5
$ss.append(createSlide());
// start the slideshow (a slideshow can't be started unless there's 2
// slides hence why we created two slides above to start with). The
// before/onBefore event will add a new slide every cycle of the slideshow.
$ss.cycle({
fx: 'scrollUp',
pause: 1,
timeout: 5000,
speed: 2000,
before: onBefore
});
});
额外说明:
要记住的一件事虽然对大多数人来说应该不是问题,但由于这确实会在每个循环中添加一张新幻灯片,因此长时间在页面上打开浏览器会开始吸收更多内容随着新元素不断被添加到 DOM 中,还有更多资源。但是,它也有一个修复程序,当您循环播放以将它们循环回原始起点时,它也可以解决,然后不需要添加新幻灯片并且可以循环播放它们;在视觉上这更容易看到然后解释
-> createSlide() = 1 2 3 4 5 6 7 (store this first results to compare with rest)
| createSlide() = 8 9 1 2 3 4 5
| createSlide() = 6 7 8 9 1 2 3
| createSlide() = 4 5 6 7 8 9 1
| createSlide() = 2 3 4 5 6 7 8
| createSlide() = 9 1 2 3 4 5 6
| createSlide() = 7 8 9 1 2 3 4
| createSlide() = 5 6 7 8 9 1 2
-< createSlide() = 3 4 5 6 7 8 9
createSlide() = 1 2 3 4 5 6 7 (this value equals the first result so no new
slides need to be added, let the process use the slides that are already added
and loop back to the beginning
额外注意事项:
我刚刚意识到的另一件事是,如果您使用上述技术,那么从技术上讲,您可以摆脱 before 事件回调,并在开始幻灯片放映之前简单地生成所有需要的幻灯片。