开发者

JQuery events mouseenter mousemove behaviour in IE

$(document).ready(function(){
  $('#outer').mouseenter(function(){
    console.log("mouse enter");
  });
  $('#outer').mousemove(function(){
    console.log("mouse move");
  });
});
<div style='width:800px;border:1px  solid red' id="outer">
 this i开发者_JS百科s test
</div>

when mouse entered the div In firefox,chrome mouseenter event is getting fired first than mouse move in case of IE mousemove event getting fired first than mouseenter. Is this know bug ? or is there any other way so that all browsers can behave in same way


[Updated Answer]

There are two ways to get around this.

1) only bind your mousemove event on the mousenter event so all subsequent events would properly fire in the same order. This involves a lot of binding and unbinding.

$(document).ready(function(){
    var outer_mousemove = function(){ console.log('mousemove') };

    $("#outer").hover(function(){
       console.log('mouseenter');
       // Attach the event listener only after
       // Mouse enter has fired
       $(this).mousemove( outer_mousemove );
    }, function(){
       $(this).unbind('mousemove', outer_mousemove );
    });
});

2) Store a variable, and only execute mousemove events when the conditions match. Much less binding/unbinding this way (This is how I would do it if it were my project):

$(document).ready(function(){
    var outer_mousemove = false;

    $("#outer").hover(function(){
       console.log('mouseenter');
       outer_mousemove = true;
    }, function(){
       console.log('mouseleave');
       outer_mousemove = false;
    }).mousemove(function(){
       if( outer_mousemove ){
         console.log('mousemove');
       }
    });
});

[Original Answer]

mouseenter is a special event created by jQuery which is why it might fire after mousemove. What you probably want is mouseover:

$(document).ready(function(){
  $('#outer').mouseover(function(){
    console.log("mouse over");
  }).mousemove(function(){
    console.log("mouse move");
  });
});

Additionally, to keep from receiving multiple mouseover events from child elements, you could test to make sure you are only acting on events generated by your object:

$(document).ready(function(){
  $('#outer').mouseover(function(e){
    if(e.target == this){
      console.log("mouse over");
    }
  }).mousemove(function(){
    console.log("mouse move");
  });
});

Finally, in my answer I used chaining (i.e. 'mouseover().mousemove()') instead of calling the selector $("#outer") twice. This just makes your page a little faster :)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜