page-break-inside:avoid equivalent for Firefox and/or IE

前端 未结 4 1393
旧时难觅i
旧时难觅i 2020-12-20 11:53

I understand that the CSS page-break-inside:avoid instruction is supposed to prevent a page break within a div when an HTML document is printed. Through searchi

4条回答
  •  我在风中等你
    2020-12-20 12:35

    For anything which is not firefox,

    .dontsplit { border: 2px solid black; page-break-inside: avoid; }
    

    will work. But not for firefox. In firefox, what you are going to have to do is check for the height and then add page-break-after: always; when it is relevant.

    On average, the margin will be 1 inch on top and bottom. So, to measure how many pixels a 10 inch page would consume, I used this:

    var pageOfPixels;
    (function(){
        var d = document.createElement("div");
        d.setAttribute("style", "height:9in;position:absolute;left:0px;top:0px;z-index:-5;");
        document.body.appendChild(d);
        pageOfPixels = $(d).height();
        d.parentNode.removeChild(d);
    })();
    

    I had a lot of divs each with a lot of paragraphs in them. So what I did was I iterated through them, and then compared the current height of the them on the current page to the pageOfPixels value.

    var currentPosition = 0;
    $('.printDiv').each(function (index, element) {
        var h = $(this).height();
        if (currentPosition + h > pageOfPixels) {
            //add page break
            $('.printDiv').eq(index - 1).css("page-break-after", "always");
            currentPosition = h;
        } else {
            currentPosition += h;
        }
    });
    

    This worked for me in firefox.

提交回复
热议问题