我发现$。推迟是解决这个问题的最佳方法。我不太了解它是如何运作的,只是解释了它的好处和解决方案。
所以基本上你想要将CSS3动画与既是异步的ajax请求结合起来。然而你想要使用回调以使效果同步或协调,即在一个新元素中将一些元素淡化为ajax然后淡入它。使用$ .Deferred的优点是你可以更多地协调这些事件#&34;尖端&#34?;办法。而不是淡出然后做一个ajax请求然后淡入,这是好的,但这意味着你必须等待你的动画完成甚至开始请求之前。使用$ .Deferred,您可以执行淡出和触发ajax请求以及完成淡入时的操作。
这是一个工作小提琴。
我将通过下面的js部分发表评论。
//Clicking the anchor triggers the loadContent function
$('a').on('click', function(){
var url = $(this).data('url');
var target = $(this).data('target');
loadContent(url, target);
});
//Slide out the existing element using a css transform
var slideOut = function($el, $target){
//Create a deffered object
var deferred = new $.Deferred();
//Slide our element out (note this has a transition through css) (double note you should use transforms for other browsers
$el.css({"-webkit-transform":"translateX(100%)"}).on('transitionend webkitTransitionEnd', function(e){
//once the transition ends resolve our deferred object and return $target
deferred.resolve($target);
});
//return the promise from the deferred object
return deferred.promise();
};
//Add the element returned from our Ajax request and slide it in
var slideIn = function(el, $target){
var $el = $(el);
$target.empty().append($el).css({height : "auto"});
//weird bug, css transition doesn't work when taken out of setTimeout (any ideas?)
setTimeout(function(){
$el.removeClass('content2');
}, 0);
};
//Make an ajax request and returns some html
//Note ajax requests return promises as well as deferred objects, I am just wrapping it here for clarity
var getData = function(url){
var deferred = new $.Deferred();
//var htmlData = "asdfasfasdf";
$.ajax({
url: url,
method : "POST",
data : { 'html': htmlData},
success: function (returnhtml) {
//resolve our deferred object and return the response
deferred.resolve(returnhtml);
},
error: function (xhr, ajaxOptions, thrownError) {
//you can reject a deferred object and then execute a different callback(s) but i'll let you figure that out
deferred.reject(thrownError);
}
});
//return the promise from the deferred object
return deferred.promise();
}
var loadContent = function(url, target){
$el = $('.content');
$target = $(target);
//Run slideOut and getData
var slidePromise = slideOut($el, $target);
var dataPromise = getData(url);
//So because we are returning promises from deferred objects in both of the above functions the following code will only run once those deferred objects have been resolved
$.when(slidePromise, dataPromise).done(function(slidePromise, dataPromise) {
//Great the ajax request is finished and our slideOut animation has finished, lets slide in the new content passing it the target element and response content
slideIn(dataPromise, slidePromise );
});
};