【问题标题】:Prevent 'mouseenter' callback function untill 'highlight' effect is complete阻止'mouseover'回调函数直到'highlight'效果完成
【发布时间】:2015-01-11 12:36:24
【问题描述】:

我遇到了与下面的 sn-p 类似的问题:

$('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 就会被允许在几分之一秒内出现。结果,您会看到它的蓝色背景。

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

如何防止这种情况发生?

【问题讨论】:

    标签: javascript jquery jquery-ui highlight mouseenter


    【解决方案1】:

    这应该适合你:

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

    【讨论】:

    • 假设我添加了第一个Lorem。由于按钮向下移动,光标有点自动越过它。有没有一种方法可以在光标悬停时将其背景变为蓝色并且 noHover 类已被删除?
    • 嗯,显然这比听起来要难。我想说在我们删除类之后在计时器内添加if( p.is(":hover")){ p.css('background', 'blue'); } ,但这不起作用,因为第一个Lorem被添加到光标下,这与用户悬停不同。我说给按钮一个 id 并使用 css 给它一个上边距,以确保用户的光标不会像 #myBtn{ margin-top:22px; } 一样落在第一个 Lorem 上方,考虑到这一点编辑上面的内容
    猜你喜欢
    • 1970-01-01
    • 2019-05-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多