jQuery onmouseover + onmouseout / hover on two different divs

拈花ヽ惹草 提交于 2019-12-19 03:42:09

问题


I've got a Problem:

Here a part of my HTML:

<div id="div_1">
    Here Hover
</div>
<div id="div_2">
    Here content to show
</div>

And here a part of my jQuery Script:

jQuery('#div_2').hide();
jQuery('#div_1').onmouseover(function() {
    jQuery('#div_2').fadeIn();
}).onmouseout(function(){
    jQuery('#div_2').fadeOut();
});

The Problem:

If i hover on the div_1, the div_2 is shown, if i hover out, the div_2 is hidden, but:

If i hover first on div_1 and then go over div_2, the div_2 is hidden fast.

I've tried this with jQuery.addClass(); after mouseout in div_1, but nothing is changing.

I dont want do make the second div in the first div... Is there another way with jQuery?

Thx Ahmet


回答1:


Here's another approach, just apply the hover to the second div as well so it stops itself being hidden:

$(function() {
  $('#div_2').hide();
  $('#div_1, #div_2').hover(function() {
      $('#div_2').stop().fadeIn();
  }, function(){
      $('#div_2').stop().fadeOut();
  });
});



回答2:


The mouseleave function might be what you are looking for.




回答3:


The simplest way to do this is to put both <div>s inside a third container <div>, then apply the hover effect to the container <div>.

By the way, you should use the hover shorthand to add the handlers.




回答4:


Try using hover() instead of mouseover() and mouseout().

Check out this documentation page : http://api.jquery.com/hover/

Hope this helps.




回答5:


Add the mouseover handler to #div_1, and the mouseout handler to #div_2. This way, #div_2 is shown when you mouseover #div_1, and it is hidden when you mouseout of #div_2 (instead of as soon as you mouseout of #div_1). The only real drawback to this is that in order to hide the second div, you must mouseover it first.

Something like this:

jQuery('#div_2').hide();
jQuery('#div_1').mouseover(function() {
    jQuery('#div_2').fadeIn();
});
jQuery('#div_2').mouseout(function(){
    jQuery('#div_2').fadeOut();
});



回答6:


Try This code:

$(function() {
    jQuery('#div_2').hide();
    jQuery('#div_1').mouseover(function() {
        jQuery('#div_2').fadeIn();
    });

    jQuery('#div_2').mouseout(function(){
        jQuery('#div_2').fadeOut();
    });
});


来源:https://stackoverflow.com/questions/2404478/jquery-onmouseover-onmouseout-hover-on-two-different-divs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!