等待其他功能中的动画完成

时间:2012-05-28 17:51:52

标签: jquery function events animation wait

关键词是“其他功能”

这就是我的意思:

function MyFunction()
{
     $("#bob").animate({left: 300}, 1000);
}


$('a').click(function(ev){
     ev.preventDefault();
     MyFunction();

     //How can the line below execute after the animation in MyFunction is done?
     document.location = $(this).attr('href')
}

非常感谢:)

2 个答案:

答案 0 :(得分:3)

这一条的两条路线。

回调路线:

function MyFunction(callback) {
     $("#bob").animate({left: 300}, 1000, callback);
}

$('a').click(function(ev){
     ev.preventDefault();
     MyFunction(function() { document.location = $(this).attr('href') });
}

延迟路线:

function MyFunction() {
     var def = new $.Deferred();
     $("#bob").animate({left: 300}, 1000, function() { def.resolve() });
     return def.promise();
}

$('a').click(function(ev){
     ev.preventDefault();
     MyFunction()
     .done(function() { document.location = $(this).attr('href') });
}

答案 1 :(得分:1)

function MyFunction(url)
{
     $("#bob").animate({left: 300}, 1000, function() {
         // this callback function will execute
         // after animation complete
         // so you can do the location change here
         document.location = url;
     });
}


$('a').click(function(ev){
     ev.preventDefault();
     MyFunction($(this).attr('href')); // passing the url to MyFunction()
});

很好用on()

$('a').on('click', function(ev){
     ev.preventDefault();
     MyFunction($(this).attr('href')); // passing the url to MyFunction()
});
相关问题