简体   繁体   中英

jQuery mouseover runs on mouseout

Here's my jQuery

$('#samsungShine').mouseover(function () {
    $('#samsungShineImage').animate({
        "margin-left": "304px"
    }, 700);
}).mouseout(function () {
    $('#samsungShineImage').css("margin-left", "-304px");
});

When I mouseover, it works excellent, when I mouseout, it doesn't reset, it re-plays the mouseover... here is a fiddle of the problem so you can see what I mean:

http://jsfiddle.net/2tujd/

Try mouseenter and mouseleave instead: http://jsfiddle.net/2tujd/11/

$('#samsungShine').mouseenter(function () {
    $('#samsungShineImage').animate({
        "margin-left": "304px"
    }, 700);
}).mouseleave(function () {
    $('#samsungShineImage').stop().css("margin-left", "-304px");
});

On the jQuery site , it says about using mouseout and simliarly for mouseover :

This event type can cause many headaches due to event bubbling. For instance, when the mouse pointer moves out of the Inner element in this example, a mouseout event will be sent to that, then trickle up to Outer. This can trigger the bound mouseout handler at inopportune times.

Edit: Add .stop() inside mouseleave to make sure any current animation is stopped prior to setting the margin-left .

Try this, using stop too:

DEMO

$('#samsungShine').mouseenter(function() {
    $('#samsungShineImage').animate({"margin-left":"304px"}, 700);
}).mouseleave(function(){
    $('#samsungShineImage').stop().css("margin-left", "-304px");
});

http://jsfiddle.net/2tujd/10/

I think its better to use just one handler. So you dont have any bubbling or problems with asynchronous methods.

$('#samsungShine').mouseenter(function () {
    $('#samsungShineImage').animate({
        "margin-left": "304px"
    }, 700, function() {
  $('#samsungShineImage').css("margin-left", "-304px")
  });
});

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