【问题标题】:How to associate the mouseover and mouseleave event with different targets in jquery?如何将 mouseover 和 mouseleave 事件与 jquery 中的不同目标相关联?
【发布时间】:2013-01-19 12:52:17
【问题描述】:

当您的鼠标进入按钮时,我正在使用 jquery .hover 函数来显示一个列表。但是,当我尝试将鼠标放入此列表并选择某个元素时,该列表会消失。我认为这是因为 .hover 函数与按钮而不是列表相关联。那么如何将 mouseover 事件与按钮相关联,将 mouseleave 事件与按钮和整个列表相关联呢?

【问题讨论】:

  • 你能展示一些html/code吗?
  • 请提供代码或jsFiddle
  • 将列表放在与按钮相同的元素中或使用超时,这有几个重复。
  • @chaonextdoor jsfiddle.net/ESWBz

标签: javascript jquery html mouseover mouseleave


【解决方案1】:

您不需要使用.hover,而是将 mouseenter 和 mouseleave 绑定到所需的元素。

$(thelist).on("mouseleave",function(){
    // hide the list
});
$(thebutton).on("mouseenter",function(){
    // show the list
});

【讨论】:

    【解决方案2】:

    使用状态变量表示在将鼠标从按钮移动到列表后是否应该继续显示列表。

    将鼠标悬停在列表事件上设置一些超时就可以了:

    HTML

    <input type="button" id="buttonId" value="hover" />
    <ul id="list">
        <li>item1</li>
        <li>item2</li>
    </ul>
    

    CSS

    #list {
        display: none;
    }
    

    JavaScript

    var keepshowingList = false;
    $('#buttonId').mouseover(function () {
        $('#list').show();
    });
    $('#buttonId').mouseleave(function () {
        setTimeout(function () {
            if (!keepshowingList) {
                $('#list').hide();
            }
        }, 150);
    });
    $('#list').mouseover(function () {
        keepshowingList = true;
    });
    $('#list').mouseleave(function () {
        keepshowingList = false;
        $(this).hide();
    });
    

    查看jsfiddle上的示例

    【讨论】:

      猜你喜欢
      • 2018-07-19
      • 1970-01-01
      • 2020-09-04
      • 2014-08-02
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多