阻止.mouseout事件执行

Prevent .mouseout event from executing

本文关键字:执行 事件 mouseout 阻止      更新时间:2023-09-26

我列出了这个HTML结构中的图像和描述:

<div class="canDo">
    <p>
        <img src="http://placehold.it/100x100" />
        <span>Description 1</span>
    </p>
    <p>
        <img src="http://placehold.it/100x100" />
        <span>Description 2</span>
    </p>
    <p>
        <img src="http://placehold.it/100x100" />
        <span>Description 3</span>
    </p>
    <p></p>
</div>

我用CSS隐藏<span>,并使用jQuery函数将描述添加到最后一个<p>中。HTML结构也被选择用于我的响应式布局。

$(document).ready( function() {
    $(".canDo img").mouseover( function() {
        $(".canDo img").removeClass('active').addClass('fade');
        $(this).addClass('active').removeClass('fade');
        $(".canDo p:last-child").fadeOut(function() {
            var msg = $('.canDo img.active').next('span').html()
            $(".canDo p:last-child").text(msg).fadeIn();
        });
    })
    .mouseout( function() {
        setTimeout(function(){
            $(".canDo img").removeClass('active fade')
            $(".canDo p:last-child").fadeOut();
        }, 3000);
    });
});

我遇到的问题是,当我悬停第一个项目,然后悬停第二个项目(并将鼠标保持在第二个上)时,会执行第一个项目的mouseout功能,使渐变效果和文本消失。

我该如何防止这种情况发生?

我还做了一个jsFiddle。

试试这个。。。我想这正是你想要的。如果不是,请告诉我。

http://jsfiddle.net/bpd2Ldy1/

所以。。。我所做的是将setTimeout函数的结果(返回特定的超时id)分配给变量tm。如果设置了它(意味着3秒后某个东西逐渐消失),并且用户将鼠标悬停在另一个小框上,它将清除并停止超时。这使得它不会与新的mouseover事件发生冲突。如果没有鼠标悬停.canDo,则超时将在3秒后不间断地完成。

$(document).ready( function() {
    $(".canDo img").mouseover( function() {
        $(".canDo img").removeClass('active').addClass('fade');
        $(this).addClass('active').removeClass('fade');
        if (typeof(tm) != 'undefined') {
            clearTimeout(tm);
        }
        $(".canDo p:last-child").stop().fadeOut(function() {
            var msg = $('.canDo img.active').next('span').html()
            $(".canDo p:last-child").text(msg).stop().fadeIn();
        });
    })
    .mouseout( function() { 
        tm = window.setTimeout(function(){
            $(".canDo img").removeClass('active fade')
            $(".canDo p:last-child").stop().fadeOut("slow");  
        }, 3000); 
    });
});