防止“鼠标输入”回调函数,直到“突出显示”效果完成

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

本文关键字:突出显示 显示 输入 鼠标 鼠标输入 回调 防止 函数 直到      更新时间:2023-09-26

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

$('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>