谢谢大家的关注,最后我是这样处理的:
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', 轮播).each(function(k, v) {
var li = $(v);
var nextIdx = 0;
如果(方向==='对'){
nextIter = ((k + iterCount) > (numItems - 1)) ?((k + iterCount) - numItems) : (k + iterCount);
}
别的 {
nextIter = (k - iterCount) >= 0 ?(k - iterCount) : numItems - (iterCount - k);
}
_animateTo(li, nextIter, 方向);
});