jquery : 元素高度 returns 0

jquery : element height returns 0

您好,有一个动态内容 HTML 具有以下结构

<Div id=1>
.....
</div>
and then 
<Div id=N>
.....
</div>

我正在尝试在 IE6 中打印预览(是的 IE6!) 由于 IE6 不支持 page-break-inside: avoid,我使用 jquery

在 ready() 函数中,我正在检查每个 div 的高度,然后将其添加到其他 div 的高度列表中。如果总和超过 700(例如),我会插入一个带有 page-break-after 属性的 HR 标签。

所以用这种方式我可以在 IE6 中显示分页符

但是,jquery获取元素高度returns正常情况下为0。也就是说,如果没有抛出 IE 错误,则元素高度为 0

如果存在 IE 错误,例如空引用或未定义,jquery 元素高度 returns 正确高度。

请帮忙解决这个问题

Jquery 用于添加 HR 标签以显示页面拆分的代码

//Function to show the page break
function PageBreak()
{
    var i1=0;
    var prevId='';
    var heights='';
    var CurrentDiv=0;
    var CurrentDivHeight=0;

    //For each DIV which contains the medication, show the page break at appropriate rows
    $(".divtblPrint").each(function(i) 
    {
        //Check the current Height
        //if currentHeight + sum of previous heights is > HeightToCheck then 

        CurrentDivHeight=$(this).outerHeight(true);

        if((i1+CurrentDivHeight)>HeightToCheck)
        {
            var HTML='';
            HTML+="<hr class='pagebreak' style='visibility:hidden;'/>";
            $(this).before($('<div class="new">'+HTML+'</div>'));
            //reset the counters since this is fresh page
            i1=CurrentDivHeight;
            prevId='';
            //return;
        }
        else //height not yet crossed, so keep loops
        {
            prevId=$(this).attr('id');
            i1+=CurrentDivHeight;
        }

    });

}

分页样式:

<style>.pagebreak {page-break-after: always;}</style>

我已经删除了你的评论并添加了我自己的评论。我认为主要问题是您忘记定义 HeightToCheck。另外,您还有许多未使用的代码。你可以省略它们。请检查代码段。

function PageBreak()
{
    var i1=0;
    var prevId=''; //not in use?
    var heights=''; //not in use?
    var CurrentDiv=0; // not in use?
    var CurrentDivHeight=0; // Ok
    var HeightToCheck=200; //Did you forget this?

    $(".divtblPrint").each(function(i) 
    {

        CurrentDivHeight=$(this).outerHeight(true);

        if((i1+CurrentDivHeight)>HeightToCheck)
        {
            var HTML='';
            HTML+="<hr class='pagebreak' style='visibility:hidden;'/>";
            $(this).before($('<div class="new">'+HTML+'</div>'));
            i1=CurrentDivHeight; // Should this be i1=0 ?
            prevId=''; // not in use?

        }
        else
        {
            prevId=$(this).attr('id'); // not in use?
            i1+=CurrentDivHeight;
        }
        
        alert(i1);
    });

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="divtblPrint">a</div>
<div class="divtblPrint">b</div>
<div class="divtblPrint">c</div>
<br>
<a onclick="PageBreak()">Click here to start loop</a>