Iframe.document.body.scrollHeight doubles 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 it runs in IE7; not tested on IE6. This is the same value if I use scrollHeight or offsetHeight.

This is the correct height in Firefox.

Before I fix this by simply splitting the IE / 2 value, what is the correct way to do this?

+3
javascript cross-browser iframe
Apr 21 '10 at 16:21
source share
2 answers

document.body is a viewport when IE is in Quirks mode. If the document inside your iframe is in Quirks, the scrollHeight body will be equal to the height of its viewport, i.e. default height iframe.

If you really need to get the height of the document in Quirks mode, you will need to add an extra wrapper div to measure. It is much better to fix this to make sure all of your documents use the standards regime doctrine. You should not create anything with Quirks mode in this decade.

In addition, you should not use document.all for IE sniffing (this may go wrong for other browsers that support it), you should not use iframe.document (it is non-standard and not even documented by MSDN) and you should always add 'px' units (IE can handle this well, and you need it in standard mode).

 function change_height(iframe) { var doc= 'contentDocument' in iframe? iframe.contentDocument : iframe.contentWindow.document; iframe.style.height= doc.body.offsetHeight+'px'; } 
+8
Apr 21 '10 at 17:03
source share

Try using this

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

also i change its code to use 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); 

Using $('iframe').ZIAutoHeight(); hope help

+1
Sep 23 '13 at 6:05
source share



All Articles