jQuery mouseenter mouseleave工具提示

我尝试了以下两种方法来显示每个具有类名头像的 div所附带的隐藏内容。

 

当我在页面上有多个头像元素时,第一个使用hover并且工作正常。

不幸的是,工具提示内置了可点击链接,hover不允许我点击链接。

  $('.avatar a').hover(function () { $(this).contents('div:last-child').css({ display : 'inline' }); }, function () { $(this).contents('div:last-child').css({ display : 'none' }); }); 

不幸的是,工具提示内置了可点击链接,hover不允许我点击链接。

我拼凑的编码是我在这里找到的使用mouseentermouseleave的编码。 这个也有效,它允许我点击链接。

  var hover = null; $('.avatar a').bind('mouseleave', function() { var $this = $(this).contents('div:last-child'); hover = setTimeout(function() { $this.fadeOut(400); }, 800); }); $('.avatar a').bind('mouseenter', function() { $(this).contents('div:last-child').css({display:'block'}); if (hover !== null) { clearTimeout(hover); } }); 

不幸的是,如果你鼠标hover在这些头像中的一个以上,只有最后一个被删除而其他人仍然存在。

我的问题是,当我移动到另一个时,我如何使用第二个将淡出任何有效工具提示?

我错过了什么吗? 或者完全做错了?

如果我理解正确,我认为你想要的是每个提示都有一个超时。 您可以使用.data通过将超时与每个提示相关联来实现此目的。

 $('.avatar a').on('mouseleave', function() { var $tip = $(this).contents('div:last-child'); $tip.data('hover', setTimeout(function() { $tip.fadeOut(400); $tip.removeData('hover'); }, 800)); }); $('.avatar a').on('mouseenter', function() { var $tip = $(this).contents('div:last-child').show(); var hover = $tip.data('hover'); if (hover) { clearTimeout(hover); $tip.removeData('hover'); } }); 

关于jsfiddle的现场演示

注意:我也将.bind()更改为.on()因为.bind()已弃用,我将其更改为使用.show()

原始代码中发生的情况是,当您hover在第二个提示上时,第一个提示的超时被清除,因为它们共享相同的“hover”变量。

编辑:在我的仓促中,我错误地清除了.data值。 我应该一直在使用.removeData() 。 我修复了上面的代码。

关于jsfiddle的更新演示

问题在于你的超时function..为什么你甚至使用它? http://jsfiddle.net/24MYq/9/删除:

  if (hover !== null) { clearTimeout(hover); } 

这不是你需要的,还是你需要延迟? 如果你真的需要它,我会编辑我的post并给你一些工作延迟。

E:延迟要么更高fadeOut()内部的数字,要么之后添加.delay(数字),而number是一个int值(500 – >半秒)

如果你想要在鼠标移开时将它们全部删除,你可以通过将var $this = $(this).contents('div:last-child')更改为var $this = $('.profile');

所有工具提示将同时消失,但只要您将鼠标hover在另一个头像上,超时就会重置。