如何使用JQuery在特定位置分割DIV? [英] How do I split a DIV at a specific point using JQuery?
问题描述
我正在编写一些JQuery来在特定高度拆分一些html代码. html是用户生成的,并且可能包含图像,因此我想不出一种实现此服务器端的好方法.
I an writing some JQuery to split some html code at a specific height. The html is user generated, and may contain images, so I can't think of a good way to do this server side.
我有一些这样生成的HTML:
I have some generated HTML like this:
<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像素高之前将其拆分)
I want the HTML to finally look like this: (Splitting the content before it reaches 60 pixels high)
<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()吗?
I've written this JQuery: I think I need to use .after maybe, or somehow refer back to the container div and close that. $(this).parent or $(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:
But it's giving back HTML like so:
<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的第一个问题,对不起,如果我做错了任何事情.
Any help very much appreciated.
What I really want to say in my function is split item at $this with a new div.
Thanks in advance.
First question on StackOverflow, so sorry if I've done anything incorrectly.
推荐答案
我将更改您的pagebreak
函数,以返回在分割点之后出现的一组元素.称为GetElementsAfterSplit()
.
I would change your pagebreak
function to return a set of the elements that occur after the split point. Call it GetElementsAfterSplit()
.
然后您可以执行以下操作:
Then you can do something like this:
$('div').each(function() {
var len = $(this).first().height();
if (len >= h) {
var splitElements = GetElementsAfterSplit();
// move elements from old location to new
splitElements.remove();
$(this).after($("<div class=\"split\"></div>").append(splitElements));
}
});
这篇关于如何使用JQuery在特定位置分割DIV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!