How do I split a DIV at a specific point using JQu

2019-05-24 12:17发布

问题:

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.

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>

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>

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);
    }
});

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>

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.

回答1:

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));
    }
});


回答2:

I found the same problem. Anno 2014 i came up with this solution

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


回答3:

Even Your requirement is slightly different but this may help you. Download the zip file and open html file in browser and click on button. it will automatically divide the html content.