从 Rich Bradshaw 的回答中,jQuery 中带有回调的淡出实现将是:
// This function is an alternative to jquery fadeOut.
// jQuery fadeOut changes opacity gradually, forcing the browser to refresh the page each time.
// Using CSS transitions allows the browser to use GPU to render the page, which is much faster if the DOM is big.
jQuery.fn.fadeOut = function(callback) {
let $selector = $(this[0]);
$selector.addClass('fadeOut');
$selector.on("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd",
function(e){
$selector.off(e);
$selector.removeClass('fadeOut');
$selector.css('display', 'none');
$selector.css('opacity', 1); // Revert back opacity since element is not displayed anymore
if(typeof callback === 'function')
callback();
});
$selector.css('opacity',0);
}
当然.fadeOut
:
.fadeOut {
-webkit-transition: opacity 1000ms ease-in-out;
-moz-transition: opacity 1000ms ease-in-out;
-o-transition: opacity 1000ms ease-in-out;
transition: opacity 1000ms ease-in-out;
}
然后您可以照常使用:
$('#div').fadeOut(function() { console.log('done!') };
使用淡入淡出也可以做到这一点。