jQuery onmouseover + onmouseout/悬停在两个不同的 div 上不同、两个、onmouseover、jQuery

2023-09-07 22:25:31 作者:灼情

我有一个问题:

这是我的 HTML 的一部分:

Here a part of my HTML:

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

这里是我的 jQuery 脚本的一部分:

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

问题:

如果我将鼠标悬停在 div_1 上,则会显示 div_2,如果我将鼠标悬停在外,则会隐藏 div_2,但是:

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

如果我先将鼠标悬停在 div_1 上,然后再越过 div_2,则 div_2 会快速隐藏.

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

我已经用 jQuery.addClass(); 试过了.在 div_1 中的 mouseout 之后,但没有任何变化.

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

我不想在第一个 div 中创建第二个 div... jQuery 还有其他方法吗?

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

感谢艾哈迈德

推荐答案

这是另一种方法,只需将悬停应用到第二个 div 上,这样它就不会被隐藏:

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