鼠标离开的条件逻辑

5

我有一个按钮网格,每行四个,共两行,宽度为800px,深度为400px。将鼠标悬停在任何一个按钮上会显示一个较小的层,位于按钮之上并居中显示(大小为700 x 300 px)。

我将mouseenter和mouseleave事件附加到赋予所有按钮的类上,该类交换了所有按钮的img src,并单独使用一个函数显示每个按钮的特定层元素。

因此,当您将鼠标悬停在任何一个按钮上时,所有按钮都会变灰,并且在其上显示特定的层,在鼠标离开按钮时,该层被隐藏,按钮返回默认状态。

这很好用,但是我希望防止在鼠标停留在可见层上时按钮返回其默认状态。因此,如果您将鼠标从按钮移动到其上方叠加的层上,则所有按钮仍然保持灰色。如果鼠标离开该层,则该层将被隐藏,所有按钮将恢复为默认状态。

我尝试创建一个全局JavaScript变量,以防止当鼠标停留在可见层上时mouseleave事件触发,并在鼠标进入可见层时设置该变量,但是mouseleave事件在我设置全局变量之前就已经触发了...我陷入了一个鸡生蛋的循环?

我在这里设置我的mouseenter/leave:

    window.lyrEntered = false;

    jQuery(function () {
        $(".img-swap").mouseenter(
      function () {
          $(".img-swap").each(function () {
             this.src = this.src.replace("_on", "_off");
          });
      });
        $(".img-swap").mouseleave(
      function () {
          //if layer entered, keep button state
          if (lyrEntered) {

          } else {
              //reset buttons if layer entered is false
              $(".img-swap").each(function () {
                  this.src = this.src.replace("_off", "_on");
                  //reset button state
                  window.lyrEntered = false;
              });

          };
      });
    });
    function showIt(lyr) {
        $(lyr).show();
    }

在每个按钮上,我将图层设置为显示:
<img src="images/img1.jpg" alt="img1" class="img-swap" id="img1" onmouseover="showIt('#layer1');" onmouseout="$('#layer1').hide();" />

在每个层面上,我试图设置全局变量,以防止mouseleave事件触发并将按钮重置为它们的默认状态:

<div id="layer1" onmouseout="$('#layer1').hide();window.lyrEntered = false;" onmouseover="$('#layer1').show();window.lyrEntered = true; ">[content here]</div>

当然了,在这里设置全局变量太晚了,因为在全局变量被设置为true之前,按钮的mouseleave事件就已经被触发了。


http://jsfiddle.net/ - 在这里尝试制作一个示例,以便每个人都可以看到您所描述的操作。 - Viktor S.
2个回答

1

这不是一个理想的情况,但您可以在 JavaScript 中使用变量:

var layerTimeout;

关于按钮的使用

onmouseout="layerTimeout = setTimeout(function(){$('#layer1').hide();},100);"

当您进入该层时,请在触发之前清除超时:

clearTimeout(layerTimeout);

对于您的图像,您也可以使用超时,在进入该层时清除两个超时。

正如我之前所说,我不认为这种解决方案非常干净,但它肯定可以帮助您。


0

我认为这样的东西会起作用

$('your_top_layer_element').on('mouseenter', function() {
    $(".img-swap").each(function () {
        this.src = this.src.replace("_on", "_off");
    });
});

基本上,当您在顶层悬停时,正在执行与悬停在img-swap上相同的操作


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接