简体   繁体   中英

Prevent .mouseout event from executing

I made a listing of images and description in this HTML structure:

<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>

I hide the <span> with CSS and add the description into the last <p> using a jQuery function. The HTML structure is chosen to work with my responsive layout as well.

$(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);
    });
});

The problem I'm having is that when I hover the first item and then the second item (and keep the mouse on that second one) the mouseout function from the first item is executed, making the fading effect and the text disappear.

How can I prevent that from happening?

I also made a jsFiddle .

try this... I think it's what you want. let me know if it's not.

http://jsfiddle.net/bpd2Ldy1/

so... what I did was assign the result of the setTimeout function (which returns a specific timeout id) to the variable tm . If it is set (meaning something is fading out after 3 seconds), and the user mouses-over another little box, it will clear and stop the timeout. that allows for it to not conflict with the new mouseover event. if nothing .canDo is moused-over, the timeout will complete uninterrupted after 3 seconds.

$(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); 
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM