【问题标题】:jquery hover on item stuck in infinite loop/starts blinking itemsjquery悬停在无限循环中的项目上/开始闪烁项目
【发布时间】:2013-02-22 00:42:24
【问题描述】:

请在下面查看我的代码。我想要的只是:

  • 我所有的物品都绝对定位
  • 当我将鼠标悬停在 item1 上时,我希望 item2、item3 显示
  • 当我将鼠标悬停在 item2 上时,我希望 item3 隐藏
  • 当我点击 item2 时,我在 item3 仍然隐藏时执行了一些功能

使用下面的代码,如果我将鼠标悬停在 item2 上,它会开始闪烁 item2 和 item3。

我做错了什么?

jsFiddle:

http://jsfiddle.net/z9Unk/53/

HTML

<div class="item1">
  item1
</div>
<div class="item2">
    item2
</div>
<div class="item3">
    item3
</div>

CSS:

item1 {
    position:absolute;
    width:150px;
    height:150px;
    background-color:red;
    top:5%;
}

.item3, .item2 {
    position:absolute;
    width:50px;
    height:50px;
    background-color:green;
    top:8%;
    left:1%;
    display:none;
}

.item3 {
    top:18%;
}

JS:

var item1 = $(".item1");
var item2 = $(".item2");
var item3 = $(".item3");

item1.hover(
    function() {
      item2.show();
      item3.show();
    },
    function() {
      item2.hide();
      item3.hide();
    }

);

item2.hover(
    function() {
      item3.hide();
    },
    function() {
    }

);

item2.click(
    function() {
        alert("Perform some function");
    }
);

【问题讨论】:

    标签: javascript jquery html css


    【解决方案1】:
    <div class="item1">
      item1
        <div class="item2">
            item2
        </div>
        <div class="item3">
            item3
        </div>
    </div>
    

    你应该重构你的 html

    item2 在 item1 之外,所以当你在 item2 上移动时,item1 的 mouseleave 会触发然后触发 item1 的 mouseenter

    【讨论】:

      【解决方案2】:

      您需要使用事件监听器,否则您的代码只是自顶向下运行。

      【讨论】:

        【解决方案3】:

        如果你不想重构你的 HTML,你可以为 item3 上的 onhover 编写另一个函数

        item3.hover(
        function() {
             item2.show();
          item3.show();
        },
        function() {
        }
        

        );

        http://jsfiddle.net/z9Unk/55/

        干杯

        【讨论】:

          【解决方案4】:

          增加 item1 的 z-index,或者只是将 item2+3 移动到其他任何地方

          【讨论】:

            猜你喜欢
            • 2021-07-21
            • 2011-06-07
            • 1970-01-01
            • 2014-12-31
            • 1970-01-01
            • 2012-10-08
            • 2017-10-14
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多