【发布时间】:2011-12-29 10:46:10
【问题描述】:
我正在编写一些 JQuery 以在特定高度拆分一些 html 代码。 html 是用户生成的,可能包含图像,所以我想不出做这个服务器端的好方法。
我有一些像这样生成的 HTML:
<div id="1">
<p>Some Text</p>
<p>Some More Text</p>
<p>Even More Text</p>
<p>Enough Text</p>
<p>Too Much Text</p>
</div>
<div id="2">
</div>
我希望 HTML 最终看起来像这样: (在内容达到 60 像素高之前拆分内容)
<div id="1">
<p>Some Text</p>
<p>Some More Text</p>
<p>Even More Text</p>
<p>Enough Text</p>
</div>
<div id="split">
<p>Too Much Text</p>
</div>
<div id="2">
</div>
我已经编写了这个 JQuery:我想我可能需要使用 .after,或者以某种方式返回容器 div 并关闭它。 $(this).parent 或 $(this).closest() ?
var h = 60;
/*Run when (item) is bigger than height.
Check and sum height of each base element, break up into 'h' px high divs*/
function pagebreak(item, h) {
var st = 0; //st = space total
$(item).children().each(function(i, l) {
if (st + $(this).height() <= h) {
st = st + $(this).height();
} else {
$(this).append('</div><div id="split">');
st = 0;
}
});
}
$('div').each(function() {
var len = $(this).first().height();
if (len >= h) {
pagebreak($(this), h);
}
});
但它会像这样返回 HTML:
<div id="1">
<p>Some Text</p>
<p>Some More Text</p>
<p>Even More Text</p>
<p>Enough Text<div id="split"></div></p>
<p>Too Much Text</p>
</div>
<div id="2">
</div>
非常感谢任何帮助。
在我的函数中,我真正想说的是在 $this 处使用新的 div 拆分项目。
提前致谢。
关于 StackOverflow 的第一个问题,如果我做错了什么,请见谅。
【问题讨论】: