如何使用JQuery在特定点拆分DIV?

时间:2011-11-15 11:18:22

标签: jquery split height

我正在编写一些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:我想我可能需要使用。之后,或者以某种方式返回容器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的第一个问题,如果我做错了什么就很抱歉。

3 个答案:

答案 0 :(得分:2)

我会更改您的pagebreak函数以返回分割点后出现的一组元素。称之为GetElementsAfterSplit()

然后你可以这样做:

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

答案 1 :(得分:1)

我发现了同样的问题。 Anno 2014我提出了这个解决方案

    var h = 60;
    var c = 0;
    $('#1').children().each(function () {
        c += $(this).height();
        if (h < c) {
            $(this).appendTo('#2');
        }
    });

答案 2 :(得分:0)

即使您的要求略有不同,this可能会对您有所帮助。下载zip文件并在浏览器中打开html文件,然后单击按钮。它会自动划分html内容。