jquery动态添加到手风琴

时间:2011-05-03 15:24:16

标签: jquery jquery-ui jquery-ui-accordion

使用example from jQuery UI,我尝试动态地为手风琴添加一个部分(基于this),但我无法让手风琴正确调整大小。新的部分溢出了手风琴容器,当它被点击时,它会被挤压到容器中,隐藏了部分内容。见fiddle

如何添加一个部分并让手风琴调整大小?

$(function() {
    $("#accordion").accordion({
        fillSpace: true
    });

    // I want to dynamically add sections to the accordion,
    // but it doesn't resize properly...
    $("#accordion")
                .append('<h3><a href="#">New Section</a></h3><div><p>hello world</p></div>')
                .accordion("destroy")
                .accordion({ fillSpace:true })
                .accordion("resize")
        ;

    $("#accordionResizer").resizable({
        minHeight: 140,
        resize: function() {
            $("#accordion").accordion("resize");
        }
    });
});

3 个答案:

答案 0 :(得分:0)

jQuery UI Accordion从调用时获取元素大小。你必须在它上面调用某种刷新方法。

答案 1 :(得分:0)

如果删除accordionResizer(height:220px)上的height属性,一切正常。看起来你选择的高度对于内容而言太低 - 因此溢出。

如果您需要非默认高度的内容以适合内容,请在每次添加新部分时尝试动态指定accordionResizer的高度。

类似......

var height = $("#accordion h3").size() * $("#accordion h3:first").height() + 50;
      // add 50px to     allow room for the section contents.
$("#accordionResizer").height(height);

答案 2 :(得分:0)

问题和答案都很好(因为你仍然可以破坏和重新创建手风琴),但现在已经过时了,引入了jQuery 1.10.0添加了一个新的refresh方法来处理调整大小的问题。鉴于jQuery的新版本,我现在将编写如下代码:

$(function() {
    // Add the following parameters otherwise the last entry
    // added to the accordion will be active after the refresh.
    //
    $("#accordion").accordion({
        collapsible: true, // Let's you squash all of the headings
        active: false // Defaults to having all of the headings squashed
    });

    // Now you can dynamically add to the accordion and refresh it.
    //
    $("#accordion")
            .append('<h3><a href="#">New Section</a></h3><div><p>hello world</p></div>')
            .accordion("refresh"); // A graceful recreation of the accordion.
});
相关问题