【问题标题】:jquery dynamically add to accordionjquery 动态添加到手风琴
【发布时间】:2014-01-27 09:16:20
【问题描述】:
使用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");
}
});
});
【问题讨论】:
标签:
jquery
jquery-ui
jquery-ui-accordion
【解决方案1】:
如果您删除手风琴调整器 (height:220px) 上的高度属性,则一切正常。看起来您选择的高度对于内容来说太低了 - 因此溢出。
如果您需要默认高度以外的其他内容来适应内容,请尝试在每次添加新部分时动态分配手风琴调整器的高度。
类似...
var height = $("#accordion h3").size() * $("#accordion h3:first").height() + 50;
// add 50px to allow room for the section contents.
$("#accordionResizer").height(height);
【解决方案2】:
jQuery UI Accordion 从调用时获取元素大小。您必须对其调用某种刷新方法。
【解决方案3】:
问题和答案都很好(因为您仍然可以销毁和重新创建手风琴),但现在随着 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.
});