jQuery onmouseover + onmouseout / hover on two dif

2020-03-04 02:55发布

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

6条回答
Fickle 薄情
2楼-- · 2020-03-04 03:10

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

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

Hope this helps.

查看更多
做个烂人
3楼-- · 2020-03-04 03:19

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.

查看更多
smile是对你的礼貌
4楼-- · 2020-03-04 03:25

The mouseleave function might be what you are looking for.

查看更多
forever°为你锁心
5楼-- · 2020-03-04 03:26

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();
  });
});
查看更多
淡お忘
6楼-- · 2020-03-04 03:26

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();
});
查看更多
劫难
7楼-- · 2020-03-04 03:27

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();
    });
});
查看更多
登录 后发表回答