Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
539 views
in Technique[技术] by (71.8m points)

javascript - iframe.document.body.scrollHeight is double the correct value

<iframe name="asdf" id="asdf" onload="change_height(this)" src="asdf.jsp" width="250" scrolling="no" frameborder="0"></iframe>

        function change_height(iframe) {
            if (document.all) {
                // IE.
                ieheight = iframe.document.body.scrollHeight;
                iframe.style.height = ieheight;
            } else {
                // Firefox.
                ffheight= iframe.contentDocument.body.offsetHeight;
                iframe.style.height = ffheight+ 'px';

            }
        }

ieheight is twice the actual height when this runs in IE7; haven't tested on IE6. It's the same value if I use scrollHeight or offsetHeight.

It's the correct height in Firefox.

Before I patch this by just dividing the IE value /2, what's the right way to do this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

document.body represents the viewport when IE is running in Quirks Mode. If the document inside your iframe is in Quirks, the scrollHeight of the body will be equal to the height of its viewport, ie. the default height of the iframe.

If you really needed to get the document-height in Quirks Mode you would have to add an extra wrapper div to measure. A much better fix is to make sure all your documents use a Standards Mode doctype. You shouldn't be authoring anything with Quirks Mode in this decade.

Also, you shouldn't use document.all for IE sniffing (this may go wrong for other browsers that support it), you shouldn't use iframe.document (it's non-standard and not even documented by MSDN), and you should always add 'px' units (IE can cope with it fine and you need it in Standards Mode).

function change_height(iframe) {
    var doc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document;
    iframe.style.height= doc.body.offsetHeight+'px';
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...