fade在处理悬停但不点击/点击

时间:2013-12-02 19:09:32

标签: javascript jquery onclick hover fadein

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

1 个答案:

答案 0 :(得分:2)

最简单的解决方案:

$('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