问题
I'm creating a script for a printable page that's generated dynamically. Because this page is generated on the fly and the sections could have varying heights, a predetermined page-break class inserted in the markup doesn't cut it. To get around this, I'm checking the height of each with a data-print="section" attribute.
What I'm struggling with is... each data-print="section" needs to generate a running total. When that total is greater than the variable "pageHeight" it inserts to force the content to a second page. Once a page-break is inserted, it needs to start the running total over again and insert another when the total is greater than "pageHeight".
Example before "script" with break at 960px...
<div class="item" data-print="section"></div> = 400px
<div class="item" data-print="section"></div> = 200px
<ul data-print="section"> = 300px
<li>
<li>
</ul>
<div class="item" data-print="section"></div> = 50px
<div class="item" data-print="section"></div> = 100px
Example after "script" with break at 960px...
<div class="item" data-print="section"></div> = 400px
<div class="item" data-print="section"></div> = 200px
<ul data-print="section"> = 300px
<li>
<li>
</ul>
<div class="item" data-print="section"></div> = 50px
<div class="page-break"></div>
<div class="item" data-print="section"></div> = 100px
Current Script
$('[data-print=section]').each(function() {
var staticHeight = $(this).filter(':visible').outerHeight(true);
var pageHeight = 400
console.log(staticHeight)
if ($(this).height() > pageHeight) {
$(this).after( '<div class="page-break"></div>');
}
});
Thanks in advance
回答1:
Set the variable staticHeight outside the each scope and reset it when adding the page break. See here
var staticHeight = 0;
var pageHeight = 100
$('[data-print=section]').each(function() {
staticHeight += $(this).filter(':visible').outerHeight(true);
console.log(staticHeight)
if (staticHeight > pageHeight) {
$(this).after( '<div class="page-break">Page Break</div>');
staticHeight = 0;
}
});
http://jsfiddle.net/3C4x7/
I set pageHeight to 100 to get it to work on Fiddle
回答2:
Not entirely sure that I get your markup, but something like this would add a new pagebreak BEFORE the total height of sections exceeds your set page limit.
$(function(){
var pageHeight = 100,
staticHeight = 0,
pageBreak = '<div class="page-break">Page Break</div>';
$('[data-print=section]')
.filter(':visible')
.each(function() {
elHeight = $(this).outerHeight(true);
var total = elHeight + staticHeight;
if (total > pageHeight){
$(this).after(pageBreak);
console.log(staticHeight);
staticHeight = 0;
} else {
staticHeight += elHeight;
}
});
});
来源:https://stackoverflow.com/questions/21241240/dynamic-page-break-jquery