开发者

jquery dynamically add to accordion

Using the example from jQuery UI, I tried dynamically adding a section to the accordion (based on this), but I can't get the accordion to resize properly. The new section overflows the accordion container, and when it's clicked, it gets squished into the container, hiding the section contents. See fiddle.

How can I add a section and get the accordion to resize?

$(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开发者_如何学C>')
                .accordion("destroy")
                .accordion({ fillSpace:true })
                .accordion("resize")
        ;

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


If you remove the height attribute on the accordionResizer (height:220px), everything works as it should. It looks like the height you've picked is too low for the contents - hence the overflow.

If you need something other than the default height to fit the contents, try dynamically assigning the height of the accordionResizer each time you add a new section.

something like...

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


jQuery UI Accordion takes the element size from when it's called. You'd have to call some kind of refresh method on it.


The issue and answer are fine (as you can still destroy and recreate the accordion), but are dated now with the introduction of jQuery 1.10.0 adding a new refresh method which handles the resizing fine. Given the new version of jQuery, I would now write the code as follows:

$(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.
});
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜