阻止 'mouseenter' 回调函数直到 'highlight' 效果完成

Prevent 'mouseenter' callback function untill 'highlight' effect is complete

我遇到了与以下代码段类似的问题:

$('button').click(function(){
    var p = $('<p>Lorem</p>');
    $('body').prepend(p);
    p.effect("highlight", {}, 3000);
});

$(document).on('mouseenter', 'p', function(){
    $(this).css('background', 'blue');
});

$(document).on('mouseleave', 'p', function(){
    $(this).css('background', 'white');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

<button>Add</button>

正如您所注意到的,一旦第一个 Lorem 被添加到正文之前,mouseenter 就被允许持续几分之一秒。结果,您看到它的蓝色背景。

这对用户体验产生了负面影响。

如何防止这种情况发生?

这应该适合你:

$('button').click(function(){
    var p = $('<p>Lorem</p>');
    $('body').prepend(p);
  
    p.effect("highlight", {}, 3000);
  
    // give your new element a class
    p.addClass('noHover');
  
    // remove that class after the animation
    setTimeout(function() { p.removeClass('noHover'); }, 3000);
    // from my testing, you could probably stand to take the `3000` down to `2500` 
    // but I leave that to you
});

$(document).on('mouseenter', 'p', function(){
  
    // check for the added class
    if(!$(this).hasClass('noHover')){
      
        //only allow the blue hover effect if the 'noHover' class has been removed
        $(this).css('background', 'blue');
    }
  
});

$(document).on('mouseleave', 'p', function(){
    $(this).css('background', 'white');
});
#myBtn{ margin-top:22px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.2/jquery-ui.js"></script>

<button id="myBtn">Add</button>