【问题标题】:Wait for animation in other function to finish等待其他功能中的动画完成
【发布时间】:2012-06-03 01:20:06
【问题描述】:
关键词是“在其他功能中”
这就是我的意思:
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')
}
非常感谢:)
【问题讨论】:
标签:
jquery
function
events
animation
wait
【解决方案1】:
这条路线有两条路线。
回调路由:
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') });
}
【解决方案2】:
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()
});