【问题标题】:fadeIn working on hover but not onClick/click [closed]fadeIn 在悬停但不是 onClick/click [关闭]
【发布时间】:2013-12-02 19:09:32
【问题描述】:

hover() 上淡入显示子列表项,而不是click()onclick()http://jsfiddle.net/gymbry/mgMK4/

【问题讨论】:

标签: javascript jquery onclick hover fadein


【解决方案1】:

最简单的解决方案:

$('ul li').click(function (e) { //  jQuery click event. The "e" is the "event" argument
    e.stopPropagation();    //  prevents a parent elements "click" event from fireing (useul here since this asigns to inner li's as well)
    var ul = $(this).children('ul');    //  find any children "ul" in this li
    //  check if ul exist and toggle (not completely neccesary as jquery will simply preform no action if element is not found)
    if (ul.length) ul.fadeToggle('fast');
});

Working Example


$('ul li').click(function (e) { //  jQuery click event. The "e" is the "event" argument
    e.stopPropagation();    //  prevents a parent elements "click" event from fireing (useul here since this asigns to inner li's as well)
    var ul = $(this).children('ul');    //  find any children "ul" in this li
    if (ul.length) {    //  check if ul exist
        if (ul.is(':visible')) {    //  check ul is visible
            ul.fadeOut('fast');
        }
        else {
            ul.fadeIn('fast');
        }
    }
});

Example 2


请记住,上述解决方案不处理关闭时打开的同级菜单或更深层次的菜单。如需更完整的解决方案,请尝试以下方法:

$('ul li').click(function (e) {
    e.stopPropagation();
    var ul = $(this).children('ul');

    $(this).siblings().each(function(i) {
        var ul = $(this).children('ul');
        if (ul.length) if (ul.is(':visible')) {
            ul.find('ul').fadeOut('fast');
            ul.fadeOut('fast');
        }
    });

    if (ul.length) {
        if (ul.is(':visible')) {
            ul.find('ul').fadeOut('fast');
            ul.fadeOut('fast');
        }
        else ul.fadeIn('fast');
    }
});

Example 3

【讨论】:

  • 对于所提供的具体案例来说似乎过于复杂。
  • @BramVanroy 我没有完成编辑答案。而且 OP 似乎对正在发生的事情没有很好的把握,因此分解了更复杂的解决方案。此外,一个简单的解决方案不会解决很多可能出现的“问题”,例如处理同级菜单
  • 我明白了。更新后:点赞。
猜你喜欢
  • 1970-01-01
  • 2021-01-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-11
  • 2016-04-06
  • 2015-07-10
相关资源
最近更新 更多