我正在努力想出一个干净的解决方案:
function centerCarouselOn(index, callback) { var items = $('li', carousel); var middleIdx = Math.floor(items.length / 2); var direction = null; var iterCount = 0; if(index === middleIdx) return; if(index > middleIdx) { direction = 'left'; iterCount = (index - middleIdx); } else { direction = 'right'; iterCount = (middleIdx - index); } $('li', carousel).each(function(k, v) { var li = $(v); // Here I need to iterate n places to the left or right // e.g: // direction = left, iterCount = 3 // Then each li by index would need this sequence: // 0: 6, 5, 4 // 1: 0, 6, 5 // 2: 1, 0, 6 // 3: 2, 1, 0 // 4: 3, 2, 1 // 5: 4, 3, 1 // 6: 5, 4, 3 (this one moves to center - index 3) }); }
答案 0 :(得分:1)
这不包含任何动画代码,并且还假设carousel
元素是<ul>
的父<li>
。
您真正需要做的就是将最后一个元素移动到第一个位置,或将第一个元素移动到最后一个位置(取决于您移动的方向)。我还添加了1秒的<li>
,所以你应该能够看到它逐步完成。
timeout
答案 1 :(得分:0)
感谢所有人的关注,这就是我最终的表现:
function centerCarouselOn(index, callback) {
var items = $('li', carousel);
var numItems = carousel.children().length;
var middleIdx = Math.floor(items.length / 2);
var direction = null;
var iterCount = 0;
if(index === middleIdx) return;
if(index > middleIdx) {
direction = 'left';
iterCount = (index - middleIdx);
}
else {
direction = 'right';
iterCount = (middleIdx - index);
}
$('li', carousel).each(function(k, v) {
var li = $(v);
// Here I need to iterate n places to the left or right
// e.g:
// direction = left, iterCount = 3
// Then each li by index would need this sequence:
// 0: 6, 5, 4
// 1: 0, 6, 5
// 2: 1, 0, 6
// 3: 2, 1, 0
// 4: 3, 2, 1
// 5: 4, 3, 1
// 6: 5, 4, 3 (this one moves to center - index 3)
if(direction === 'right') {
for(var i = k; i < (k + iterCount); i++) {
var thisIter = i;
var nextIter = (++thisIter >= numItems) ? (thisIter - numItems) : thisIter;
console.log(k + ': ' + nextIter);
}
}
else {
for(var i = k; i > (k - iterCount); i--) {
var thisIter = i;
var nextIter = (--thisIter < 0) ? (numItems + thisIter) : thisIter;
console.log(k + ': ' + nextIter);
}
}
});
}
结果是这样的动画看起来废话,所以我只是计算最终位置(并且它作为奖励更有效):
$('li', carousel).each(function(k, v) { var li = $(v); var nextIdx = 0; if(direction === 'right') { nextIter = ((k + iterCount) > (numItems - 1)) ? ((k + iterCount) - numItems) : (k + iterCount); } else { nextIter = (k - iterCount) >= 0 ? (k - iterCount) : numItems - (iterCount - k); } _animateTo(li, nextIter, direction); });