Jquery Hide/Show 悬停时重复发生

Jquery Hide/Show happening repeatedly on hover

所以我有两个 div 正好放在彼此的顶部并且具有相同的尺寸。默认情况下应该显示 div A,但是当有人将鼠标悬停在该区域上时,div A 已被 Jquery 编程为 .hide() 并且 div B 已被编程为 .show()。同样,当悬停结束时,显示应返回默认值。我使用 .mouseover().mouseout() 函数完成了此操作。

当我不向 show()hide() 函数传递任何参数时,它工作得很好。但是假设我做了类似 .show(800).hide(800).show("slow").hide("slow") 的事情,动画会重复发生一段时间然后停止。 Div B 显示,然后隐藏,同时 Div A 隐藏和显示,反复进行。 .mouseover() / .mouseout() 函数应用于 A 和 B 的父级 div

我知道 .stop() 功能,它在很大程度上解决了问题,但还不完全。我在 Div B 上有 hyperlinked 文本,其中 link 悬停动画在显示 Div B 时一直闪烁。

这是一个 link 的网站。 http://nd2cindia.com/test_teams_display/(我目前正在使用 .show().hide() 函数,直到这个问题得到解决。)

这是我的 Jquery

$(".parent").mouseover(function () {
  $("> .A", this).hide("800");
  $("> .B", this).show("800");
});

$(".teambox").mouseout(function () {
  $("> .A", this).show("800");
  $("> .B", this).hide("800");
});

我每次都在使用:

$("selector").stop().show();
$("selector2").stop().hide();

它停止所有 运行ning 动画和 运行 从实际状态。

这是你want.I写的样式internally.you可以随意更改。

<html>
<head>
<title></title>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>

</head>
<body>

<div class="a" style="width:100px;height:100px;background-color:green; position:absolute;top:10px;left:10px;">
</div>
<div class="b" style="width:100px;height:100px;background-color:orange;position:absolute;left:10px;top:10px">
</div>


<!-- js--> 
<script type="text/javascript">
 $(document).ready(function(){
    $(".b").mouseenter(function(){
        $(this).fadeOut(1000,function(){
            $(this).mouseleave(function(){
                $(this).fadeIn(1000);
            });
        });
    });

 });
</script>

</body>
</html>

希望对您有所帮助。我建议您使用 mouseentermouseleave 而不是 mouseovermouseout.

在您的 HTML 中,您有重复的 ID (#team_name_id)。这是无效的,所以我删除了 ID 并添加了一个 class - 您应该进行自己的更改,这将导致您更新 CSS.

首先,我创建了一个命名函数,您可以将其应用于您的事件而不是匿名函数 - 这样做通常更好,因为它允许您分离您的关注点 - 并且更干。

其次,因为您正在切换,并且不需要其他逻辑 - 您可以使用单个函数。将来您可能希望将其分开,以便更好地控制和逻辑。

var hoverToggle = function () {
  // Toggling an element will bring it into view or hide it, and it will do so with a queue.
  // Anything more complex than this, you'll need to make your own queue
  $(this).find('.players_display, .beforehover').stop().toggle(800)
}

您会注意到我使用了“this”,它提供上下文并阻止事件在您的框外冒泡创造了。这也意味着它们更容易找到。

您还会注意到我使用逗号分隔的 选择器 来查找两个集合。使用 toggle 的另一个好处是它会独立处理每个元素。因此,虽然一个显示()另一个隐藏()。

我发现 hover() 是一个更好的函数调用 - 因为它使代码更整洁。只需在其中调用您的函数。如果您愿意,可以对除 hover() 之外的其他函数执行相同的操作。

$('.teambox').hover(hoverToggle, hoverToggle);

jsFiddle 演示:https://jsfiddle.net/likestothink/ndfbhw02/1/