fadeOut()回调在淡入淡出完成之前完成

Cal*_*lat 4 javascript jquery

我正在开发一个字体测试页面,它应该在点击时切换标题和段落标记的字体.哪个工作正常,但经验非常刺耳所以我想通过以下路径平滑它:

淡出 - >做字体交换 - >淡入

但代码首先运行字体交换,然后运行动画.

我有以下代码片段,我只包括jQuery,因为它是我的问题的根本原因.

// Anytime a card is clicked
$('.card').click(function(){
    // Call card by id and switch the fonts
    var id = "#" + this.parentElement.id;
    $(this).fadeOut(900,swapFont(id));
    $(this).fadeIn(500);
    // attach the above to some sort of transition callback

});

// Function to swap the font around so that the header is now the body font and the body font is now the header font
function swapFont(id) {
 // font-swap logic in here which works fine
}
Run Code Online (Sandbox Code Playgroud)

Ror*_*san 6

问题是因为fadeOut()动画(有效)是异步的.这意味着将在动画进行过程中评估下一个语句 - 因此您将看到的行为.要解决此问题,您需要使用fadeX()方法提供的回调模式.

此外,您将立即执行的结果传递swapFont()给回调,而不是在事件发生时运行的函数引用.试试这个:

$('.card').click(function(){
  var id = "#" + this.parentElement.id;
  $(this).fadeOut(900, function() {
    swapFont(id);
    $(this).fadeIn(500);
  });
});
Run Code Online (Sandbox Code Playgroud)