我已经设法达到这个目的,它对于实心宽度div很有用,但是当div的宽度发生变化时,无法解决如何操作它的问题。
问题:如何使此功能考虑到每一轮后的不同div宽度?
var horizontalScroller = function($elem) {
var left = parseInt($elem.css("left"));
var temp = -1 * $('#horizontalScroller li').width();
if(left < temp) {
left = $('#horizontalScroller').width();
$elem.css("left", left);
}
$elem.animate({ left: (left-60) }, 2000, 'linear', function () {
horizontalScroller($(this));
});
}
$(document).ready(function() {
var i = 0;
$("#horizontalScroller li").each(function () {
$(this).css("left", i);
i += $(this).width();
horizontalScroller($(this));
});
});
工作示例(固定宽度):http://jsfiddle.net/GL5V3/
工作示例(宽度不同):http://jsfiddle.net/wm9gt/
答案 0 :(得分:4)
这很有趣,了解你的代码是如何工作的,但在我这样做之前......
我把它重写为:(working fiddle)
function horizontalScroller(ulSelector) {
var horizontalSpan=0;
var collection=[];
function animate(index) {
var cur=collection[index];
var left=parseInt(cur.elem.css('left'));
if(left < cur.reboundPos) {
left+=horizontalSpan;
console.log(left);
cur.elem.css('left',left);
}
cur.elem.animate(
{ left: (left-60) },
2000,
'linear',
function () {animate(index)}
);
}
$(ulSelector).find('li').each(function() {
var $this=$(this);
var width=$this.width();
$this.css('left',horizontalSpan);
collection.push({reboundPos: -1 * width, elem: $this});
horizontalSpan+=width;
animate(collection.length-1);
});
console.log(collection);
console.log(horizontalSpan);
}
$(document).ready(function() {
horizontalScroller('#horizontalScroller');
});
然后我回到你的代码并做了这个:
var horizontalSpan = 0;// swapped i for a "global" variable
var horizontalScroller = function($elem) {
var left = parseInt($elem.css("left"));
var temp = -1 * $elem.width();// updated to the correct width
if(left < temp) {// now out of bounds is properly calculated
left += horizontalSpan;// proper "wrapping" with just one addition
$elem.css("left", left);
}
$elem.animate({ left: (left-60) }, 2000, 'linear', function () {
horizontalScroller($(this));
});
}
$(document).ready(function() {
$("#horizontalScroller li").each(function () {
$(this).css("left", horizontalSpan);// horizontalSpan!!!
horizontalSpan += $(this).width();// horizontalSpan!!!
horizontalScroller($(this));
});
});
如果您有疑问或想稍微调整一下。我很乐意帮助你。但我希望你能自己管理。
P.S。我最初的评论是粗鲁的,你是水平滚动是好的竖起大拇指(但你希望这些.width()
部分电话的价值观有所不同)