我正在编写一个选取框脚本,因为我不喜欢大多数选取框脚本在选取框到达最后一个项目时(考虑使用 ul,所以最后一个项目是最后一个 li),它会等到该项目离开屏幕,并且然后重置 ul 的位置,然后开始滚动。
我的方法是创建 ul 的克隆,将其附加在当前 ul 之后,并开始滚动,然后在完全隐藏后删除原始 ul。
除了一件事之外,这几乎是完美的。当您调用该函数时,它会生成 setTimout 所需的时间。此 setTimout 用于创建新的 UL 并将其设置为移动。
这适用于第一个循环,但随后出现故障。
这有点难以解释,但似乎应该在第二次调用超时,而不是等待时间,它只是立即调用自己。有关示例,请参阅http://webspirited.com/marquee.html
对于一个工作示例。javascript代码如下:
var count = 0;
$('document').ready(function () {
//generate some random rows
for (var i = 0; i <= 20; i++)
$('.ulscroll').append('<li>Content ' + i + '</li>');
//add one row so we can see its the last
$('.ulscroll').append('<li>Last Item</li>');
//set the ul's width
var width = 0;
$('.ulscroll').children('li').each(function () {
width += $(this).outerWidth();
});
log('ul width: ' + width);
$('.ulscroll').width(width);
//activate the marquee
marquee('.ulscroll', 1, false);
});
function marquee(id, speed, sub) {
//next two lines debugging purposes only
count += 1;
log('Marquee ran ' + count + ' times');
//store copy of speed sent it(to pass for recursion)
var s1 = speed;
//set speed to 10*
speed = speed * 10;
//store parent width, and own width (if sub then add on width of parent div)
var pwidth = $(id).parent('div').outerWidth();
var width = (sub ? $(id).width() + pwidth : $(id).width());
//set timeout
var t = (width - pwidth) * speed;
setTimeout(function () {
var clone = $(id).clone().css('left', pwidth);
$(id).addClass('oldul');
$(id).after(clone);
marquee(id + ':not(.oldul)', s1, true);
}, t);
$(id).animate({
left: '-=' + width
}, width * speed, 'linear', function () {
$(this).remove();
});
}
function log(text) {
$('#log').append('<div>' + text + '</div>');
}
解决方案
该问题是由使用 :not(.ulold); 传入选择器引起的。这是修改后的 setTimeout
setTimeout(function(){
var clone = $(id).clone().css('left', pwidth);
$(id).addClass('oldul');
var idx = id.split(':');
idx = idx[0];
log('idx: '+idx);
$(idx).after(clone);
marquee(idx+':not(.oldul)', s1, true);
},t);