我制作了一个网站,需要对比包含父级更长的字符串进行动画处理。
这是网站:Here
如果单击“下一步”,您可以看到多个名称很长的饲养员页面,需要从左到右进行动画处理,但这只会在 10 或 15 秒后发生,并且需要很长时间才能启动。
现在我已经检查了我的代码,这是我创建函数的地方:
function newsTicker() {
console.log('newsTicker')
verifyLength();
$('.breeder').not('.short-breed-name').each(function() {
var breederNameWidth = $(this).find('.breeder_name').width();
var divBreederNameWidth = $(this).find('.breeder_name_div').width();
var diff = Math.max(parseInt(breederNameWidth - divBreederNameWidth),0);
// console.log('diff:',diff)
$(this).find('.breeder_name').animate({
marginLeft: -diff
}, 3000,
function(){
$(this).animate({
marginLeft : 0
},3000)
})
})
}
function verifyLength() {
// console.log('verifyLength')
$('.breeder.visible').each(function() {
// debugger
var breederNameWidth = $(this).find('.breeder_name').width() + 10;
var divBreederNameWidth = $(this).find('.breeder_name_div').innerWidth();
if(breederNameWidth < divBreederNameWidth) {
$(this).addClass('short-breed-name');
$(this).find('.breeder_name').css({'width':'100%','text-align':'center'})
}
})
}
这就是我调用 newsTicker 的地方:
function breederAnimate(){
verifyLength();
newsTicker();
setInterval(newsTicker, 1000);
}
为什么我的时间在 1 到 3 秒之间却这么慢?
最佳答案
您应该调用 setTimeout
而不是 setInterval
,因为您只希望动画运行一次。您每秒都会重新启动动画
此外,当您单击下一个或上一个时,您应该取消现有的 setIntervals
关于javascript - setInterval运行非常慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25851529/