我有一个函数也可以按我的要求工作,只是它看起来真的很乱而且臃肿,所以我想知道,有没有更好的方法来编写下面的代码?
function careerFlyIn(){
var distance = $('.row').offset().top,
$window = $(window);
var distance = distance - 200;
var flyInR = $('.path-description');
var flyInL = $('.path-title');
$window.scroll(function() {
if ( $window.scrollTop() >= distance ) {
$('.career-path .row:first-child').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function () {
$('.career-path .row:nth-child(2)').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function () {
$('.career-path .row:nth-child(3)').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function () {
$('.career-path .row:nth-child(4)').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function () {
$('.career-path .row:nth-child(5)').find(flyInL).animate({ 'left' : '0px' } ,400, 'easeOutBounce', function () { });
});
});
});
})
$('.career-path .row:first-child').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function () {
$('.career-path .row:nth-child(2)').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function () {
$('.career-path .row:nth-child(3)').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function () {
$('.career-path .row:nth-child(4)').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function () {
$('.career-path .row:nth-child(5)').find(flyInR).animate({ 'right' : '0px' } ,400, 'easeOutBounce', function () { });
});
});
});
})
}
});
};
最佳答案
创建要设置动画的元素列表并在列表上使用异步递归。
function animate(elements, callback)
{
if (elements.length){
elements.eq(0).find(flyInR).animate({ 'right' : '0px' }, 400, 'easeOutBounce');
elements.eq(0).find(flyInL).animate({ 'left' : '0px' }, 400, 'easeOutBounce', function (){
// Do the remainder of the list (after first item)
animate(elements.slice(1), callback);
});
}
else {
// All done, call the final callback
callback();
}
}
animate($('.career-path .row'), function()
{
// do something when all items have finished animating
});
您可以将此模式应用于任何一组类似的异步操作。在此示例中,左右动画并行运行,但只有一个会触发下一个事件(在本例中为左)。
关于javascript - 优化 jQuery 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18274056/