使用Jquery或css3显示使用悬停显示

时间:2013-01-10 19:58:23

标签: jquery hover

我有一个导航栏,可以在悬停时显示内容。您可以在此处查看有效的演示:http://codepen.io/anon/pen/wjciG

正如你所看到的,它运作得相当好,但它有点儿麻烦。

我的jquery很简单,绝对可以改进:

$("#navButtons li").hover(function(){
     $(this).find("span#tooltip").stop().fadeIn(300);
}, function(){
     $(this).find("span#tooltip").stop().fadeOut(300);
});

span#tooltip绝对位于悬停链接之下,因此当用户将鼠标悬停在链接上然后尝试将鼠标悬停在工具提示/框上时,它会闪烁(因为有一段时间用户不是徘徊在任何事情上)。我需要允许用户将鼠标悬停在元素上,看到框淡入,然后允许用户将鼠标悬停在框上并单击可能位于其中的任何链接或内容。

有没有更好的方法使用Jquery或CSS3来编写它,以获得更平滑,更可靠的结果?

4 个答案:

答案 0 :(得分:0)

使用工具提示的CSS。将padding-top:20px; margin-top:-20px添加到span#tooltip会使提示的位置与图标一样高;因此,没有办法“鼠标移除”这些链接。由于图标的z比工具提示高,因此从图标移动到图标没有任何不良影响。

enter image description here

(为说明目的添加了大纲)

答案 1 :(得分:0)

一种可能的替代方法是使用CSS来实现淡入和淡出效果。

我整理了一个快速而肮脏的例子here来说明如何做到这一点。有明显的警告并非所有浏览器都支持它,但在当前示例中禁用javascript的用户也是如此。 CSS版本仍然可以工作,它只会出现并消失而不会褪色。

同样只是隐藏具有不透明度的元素将使它们更易于访问。

另一种选择:)

答案 2 :(得分:0)

奇怪的是,我遇到了传递项目的同样问题。解决方案是在使用javascript的setTimeout方法隐藏工具提示之前添加延迟。

这是代码:

var closeTip = new Array();
$("#navButtons li").each(function (i) {
  var $this = $(this);
  $this.hover(function () {
    clearTimeout(closeTip[i]); // cancell closing tooltip
    if ($this.hasClass('visible')) {
      return false; // we are still on, do nothing else
    } else {
      // we moved to another "li" element so reset everything
      $("#navButtons li").removeClass('visible');
      $("span.tooltip").hide(); 
    }
    // show "this" tooltip and add class "visible" as flag
    $this.addClass('visible').find("span.tooltip").stop().fadeIn(300).mouseenter(function () {
      clearTimeout(closeTip[i]); // cancell closing itself even if we leave 
    });
  },
  function () {
    // delay closing tooltip unless is cancelled by another mouseenter event
    closeTip[i] = setTimeout(function () {
      $this.removeClass('visible').find("span.tooltip").stop(true, true).fadeOut();
    }, 500);
  });
}); // each

由于您不应在同一文档中使用相同的 ID ,因此我将所有id="tooltip"转换为class="tooltip"

在脚本中还注意到我正在向hovered元素添加class="visible"并将相同的css属性设置为该选择器

#navButtons li.hours:hover span, #navButtons li.hours.visible span {
  background-position: -1px -35px;
}
#navButtons li.login:hover span, #navButtons li.login.visible span {
  background-position: -41px -35px;
}
#navButtons li.newsletter:hover span, #navButtons li.newsletter.visible span {
  background-position: -83px -35px;
}

...所以当我们从按钮移动到工具提示时,按钮不会闪烁。

参见 JSFIDDLE

答案 3 :(得分:0)

jsFiddle DEMO

您忘了向 #navButtons li span CSS选择器添加一个属性。

margin-bottom: 25px; /* 20px is the tooltip distance, but a little extra helps */

这可行的原因是因为margin-bottom是“盒子模型”的一部分,hover事件可以监视任何状态变化。同时更改工具提示id,以便类名,因为您不能在网页上两次使用相同的id