我目前有使用css和jquery制作动画树结构的基本代码,但由于对jquery的了解有限,我在参数方面遇到麻烦,请参见下文。在第3行中,我要说的是如果li的类扩展了,那么添加一个将打开和关闭li的过渡。如果尝试使用我的DEMO,您会发现它适用于顶层li,但不适用于树中的每个li。有没有一种方法可以使jQuery判断结构中的li是否扩展,而不是将每个li都一样对待?谢谢

$(function () {
    $("li").click(function () {
        var expanded = $(this).is(".expanded");
        if (expanded)
        {
            $(this).transition({ 'max-height': '20px', overflow: 'hidden' }, 500, 'in', function () {$(this).removeClass("expanded"); });
        }
        else
        {
            $(this).transition({ 'max-height': $(this).get(0).scrollHeight, overflow: ''}, 500, 'out', function () { $(this).addClass("expanded"); });
        }
    });
});

最佳答案

发生的事情是事件到达父级,元素崩溃了。

您需要使用.stopPropagation来防止这种情况。

这将告诉事件仅在其匹配的最低级别执行,因此事件不会向上扩展到展开的父级LI。

$(function () {
    $("li").click(function (e) {
        e.stopPropagation()
        var expanded = $(this).is(".expanded");
        if (expanded)
        {
            $(this).transition({ 'max-height': '20px', overflow: 'hidden' }, 500, 'in', function () {$(this).removeClass("expanded"); });
        }
        else
        {
            $(this).transition({ 'max-height': $(this).get(0).scrollHeight, overflow: ''}, 500, 'out', function () { $(this).addClass("expanded"); });
        }
    });
});


Fiddle

07-25 22:02
查看更多