单击并不总是触发切换事件

时间:2011-12-11 23:49:51

标签: javascript jquery css css-position

我有一种imagemap,它基本上是很多绝对定位的div,当点击它时,它会显示或隐藏工具提示。看起来非常棒,除了事实,它并不总是“有效”。这听起来很愚蠢,但有时我会不得不点击几次来触发事件。也许我只是没有点击力不够? ;)

标记

<div class="container">
  <img src="img.png" />
  <div class="trigger"
    <div class="tooltip">
      Awesome tooltip is awesome!
    </div>
  </div>
</div>

风格

.container {
  width:100px;
  height:100px;
  position:relative; }

img {
    position:relative; }

.trigger {
  width:50px;
  height:50px;
  position:absolute;
  top:50px;
  left:50px; }

.tooltip {
  width:100px;
  height:20px;
  position:absolute;
  top:35px;
  left:35px;
  display:none; }

的Javascript

$(".trigger").toggle(function () {
      $(this).children(".tooltip").stop(true, true).fadeTo(200, 0.9);
      $(this).siblings(".trigger").children(".tooltip").stop(true, true).fadeOut(200);
   }, function () {
      $(this).children(".tooltip").fadeOut(200);
   });

简化了标记和CSS,但想象一下,我在图像上有几个工具提示。当我打开一个工具提示时,应关闭所有其他工具提示。我猜这是出问题的地方,但我看不出错误。

在同一网站上的类似功能中,我已经半动态地添加了一些ID,并隐藏了所有ID:not(ID),但我简直不相信这是必要的。

修改 看哪,小提琴:http://jsfiddle.net/CfYRv/

4 个答案:

答案 0 :(得分:2)

将您的javascript更改为

$(".trigger").click(function () {
      $(".tooltip").fadeOut();
      $(this).children(".tooltip").fadeIn();
   });

答案 1 :(得分:1)

尔加!需要完成我的作业,但很长的答案很短:切换在这里不起作用,因为你切换一个子菜单,然后点击另一个。这隐藏了第一个子菜单,但它仍然被认为是开放的(它只是隐藏)。因此,您需要单击它两次才能打开它...我一起攻击了另一种选择,但它不是最好的代码。它至少可以让你知道需要做什么:

http://jsfiddle.net/uj2A4/

$(".trigger").click(function () {
      if($(this).hasClass("active"))
          $(".tooltip",this).fadeOut(200);
      else {
          $(this).children(".tooltip").stop(true, true).fadeTo(200, 0.9);
          $(this).siblings(".trigger").children(".tooltip").stop(true, true).fadeOut(200);
      }
      $(this).toggleClass("active");
      $(this).siblings(".trigger").removeClass("active");
   });

答案 2 :(得分:0)

让我们使用点击:http://jsfiddle.net/CfYRv/3/

,而不是切换

这将“活动”工具提示指定为css类“ttactive”。单击“某个触发器”将淡出每个活动的工具提示,并激活您刚刚单击的那个。如果您刚刚点击的那个是活动的那个,它所做的就是淡化那个。

答案 3 :(得分:0)

你可能仍然会以这种方式切换:

 $(".trigger").click(function () {
  $(this).children(".tooltip").stop(true, true).toggle();
  $(this).siblings(".trigger").children(".tooltip").stop(true, true).fadeOut(200);
 });
相关问题