<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.
B开发者_StackOverflowefore I patch this by just dividing the IE value /2, what's the right way to do this?
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';
}
Try to use this
function change_height(iframe) {
var doc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document;
iframe.style.height= doc.body.scrollHeight+'px';
}
also i modify it's code to use by jquery
(function($) {
$.fn.ZIAutoHeight = function() {
var t = this, doc = 'contentDocument' in t[0]? t[0].contentDocument : t[0].contentWindow.document;
t.css('height', doc.body.scrollHeight+'px');
}
})(jQuery);
Usage $('iframe').ZIAutoHeight();
hope that's help
精彩评论