JavaScript allows IFRAME adaptive height instance

Source: Internet
Author: User

At work, we have encountered an IFRAME embedded page highly adaptive problem. Because we don't know how high the IFRAME content page will be loaded, and don't want to appear on the page ugly scroll bar, this time we can use JavaScript to dynamically let the iframe adaptive height.


Preparatory work

We prepare a homepage a.html, as well as two pages for embedding IFrame respectively for iframeh.html and iframeh1.html, the content can be arbitrarily added, the actual application may be the content generated in the background.
To demonstrate, we add the following code to the main page a.html:

<div class= "OPT_BTN" >
<button onclick= "GetData (' Iframeh ');" > Loading Content 1</button>
<button onclick= "GetData (' iframeH2 ');" > Loading Content 2</button>
</div>
<iframe src= "iframeh.html" id= "ifrm" frameborder= "0" width= "100%" scrolling= "no" marginheight= "0" marginwidth= "0" Onload= "Setiframeheight (this.id)" ></iframe>

What we want to achieve is, click two buttons respectively, the iframe load different content, the IFRAME can not appear in the scroll bar.

Javascript

First, we use JavaScript to dynamically change the SRC value of the IFRAME, that is, when the two buttons are clicked, the IFRAME loads the different page contents. The button buttons in the code call the Custom Function GetData () to achieve the effect of switching content.

function GetData (IFM) {
document.getElementById ("ifrm"). src = ifm+ '. html ';
}

Then, we pay attention to the contents of the IFRAME, because we do not know the content of the IFRAME, if you set the height of the iframe first, it is likely that when the page content is too long will appear scroll bar, this is not what we want. So we use JavaScript to dynamically get the height of the iframe page, and then set the height of the iframe.
After the IFRAME is fully loaded, that is, the onload, call Setiframeheight (), after the iframe content loaded, can get the height of the IFRAME, and then reset the height of the IFRAME, the following is the collation of the code:

function Setiframeheight (ID) {
var ifrm = document.getElementById (ID);
var doc = ifrm.contentdocument? Ifrm.contentdocument:
Ifrm.contentWindow.document;
ifrm.style.visibility = ' hidden ';
Ifrm.style.height = "10px"; Reset to minimal height ...
Ifrm.style.height = Getdocheight (DOC) + 4 + "px";
ifrm.style.visibility = ' visible ';
}

function Getdocheight (DOC) {
Doc = Doc | | Document
var BODY = doc.body, html = doc.documentelement;
var height = Math.max (body.scrollheight, Body.offsetheight,
Html.clientheight, Html.scrollheight, html.offsetheight);
return height;
}

Classic Code IFrame Adaptive height, passed in Ie6/ie7/ie8/firefox/opera/chrome/safari test.


<iframe src= "http://www.111cn.net/" id= "Iframepage" name= "Iframepage" frameborder=0 "Scrolling=no" width= "100%" Onload= "Iframeheight ()" ></iframe>javascript Code:
<script type= "Text/javascript" language= "JavaScript" >
function Iframeheight () {
var ifm= document.getelementbyid ("Iframepage");
var subweb = Document.frames? document.frames["Iframepage"].document:ifm.contentdocument;
if (IFM!= null && subweb!= null) {
Ifm.height = SubWeb.body.scrollHeight;
}
}
</script>

The following compatibility is better

<script language= "javascript" type= "Text/javascript" >
function Dyniframesize (down) {
var ptar = null;
if (document.getElementById) {
Ptar = document.getElementById (down);
}
else{
Eval (' Ptar = ' + down + '; ');
}
if (Ptar &&!window.opera) {
Begin resizing IFRAME
ptar.style.display= "Block"
if (ptar.contentdocument && pTar.contentDocument.body.offsetHeight) {
NS6 syntax
Ptar.height = PTar.contentDocument.body.offsetHeight +20;
Ptar.width = ptar.contentdocument.body.scrollwidth+20;
}
else if (ptar.document && pTar.Document.body.scrollHeight) {
ie5+ syntax
Ptar.height = PTar.Document.body.scrollHeight;
Ptar.width = PTar.Document.body.scrollWidth;
}
}
}
</script>
<iframe src = "/default2.aspx" frameborder= "0" marginheight= "0" marginwidth= "0" frameborder= "0" scrolling= "Auto" id= "IFM" name= "IFM" onload= "javascript:dyniframesize" (' IFM '); "width=" 100% ">
</iframe>

IFrame content unknown, highly predictable

At this point, we can add a default CSS min-height value to it, and then use JavaScript to change the height. Common compatibility codes are:


Document.domain = "caibaojian.com";
function Setiframeheight (IFRAME) {
if (IFRAME) {
var Iframewin = Iframe.contentwindow | | Iframe.contentDocument.parentWindow;
if (iframeWin.document.body) {
Iframe.height = IframeWin.document.documentElement.scrollHeight | | IframeWin.document.body.scrollHeight;
}
}
};

Window.onload = function () {
Setiframeheight (document.getElementById (' external-frame '));
};

Just modify the ID of the IFRAME above. Or you can directly in the IFRAME to write code, we generally do not pollute the HTML code, we recommend the use of the above code.

<iframe src= "backtop.html" frameborder= "0" scrolling= "no" id= "External-frame" onload= "Setiframeheight" (This) > </iframe>

Multiple IFRAME Cases

<script language= "JavaScript" >
Enter a list of the names of the IFRAME that you want to automatically adjust height based on the height of the page
Separate the IDs of each iframe with commas. For example: ["myframe1", "myframe2"], you can have only one form, no commas.
Define the ID of the IFRAME
var iframeids=["Test"];
If the user's browser does not support IFrame to hide the iframe and yes to hide, no means no hidden
var iframehide= "yes";
function Dyniframesize ()
{
var dyniframe=new Array ()
for (i=0; i<iframeids.length; i++)
{
if (document.getElementById)
{
Automatically adjust the iframe height
Dyniframe[dyniframe.length] = document.getElementById (Iframeids[i]);
if (Dyniframe[i] &&!window.opera)
{
dyniframe[i].style.display= "Block";
if (dyniframe[i].contentdocument && dyniframe[i].contentdocument.body.offsetheight)//If the user's browser is Netscape
Dyniframe[i].height = Dyniframe[i].contentdocument.body.offsetheight;
else if (dyniframe[i). Document && Dyniframe[i]. Document.body.scrollHeight)//If the user's browser is IE
Dyniframe[i].height = Dyniframe[i]. Document.body.scrollHeight;
}
}
To handle the display of browsers that do not support IFRAME based on the parameters set
if ((document.all | | document.getelementbyid) && iframehide== "No")
{
var tempobj=document.all? Document.all[iframeids[i]]: document.getElementById (iframeids[i]);
tempobj.style.display= "Block";
}
}
}
if (Window.addeventlistener)
Window.addeventlistener ("Load", dyniframesize, false);
else if (window.attachevent)
Window.attachevent ("onload", dyniframesize);
Else
Window.onload=dyniframesize;
</script>
Demo Three

Called for the ID of the known IFRAME

function Iframeautofit (iframeobj) {
settimeout (function () {if (!iframeobj) return;iframeobj.height= (iframeobj.document?) iframeObj.Document.body.scrollHeight:iframeObj.contentDocument.body.offsetHeight);},200)
}
Demo Four

The content width changes the iframe highly adaptive

<iframe src= "backtop.html" frameborder= "0" scrolling= "no" id= "test" onload= "this.height=100" ></iframe>
<script type= "Text/javascript" >
function Reinitiframe () {
var iframe = document.getElementById ("test");
try{
var bheight = iframe.contentWindow.document.body.scrollHeight;
var dheight = iframe.contentWindow.document.documentElement.scrollHeight;
var height = Math.max (bheight, dheight);
Iframe.height = height;
Console.log (height);
}catch (ex) {}
}
Window.setinterval ("Reinitiframe ()", 200);
</script>


Open the Debug Run window to see the run.

The adaptive height of iframe under cross-domain

Cross-domain, because of JS's homology strategy, the parent page of JS can not get to the height of the iframe page. Need a page to do the proxy.
The method is as follows: Suppose a page under www.a.com a.html to include a page under Www.b.com c.html.
We use another page under Www.a.com to act as proxies, to get the height of the IFRAME page and to set the height of the iframe element agent.html.

The a.html contains an iframe:

<iframe src= "http://www.b.com/c.html" id= "iframe" frameborder= "0" scrolling= "no" style= "border:0px"; ></iframe>
Add the following code to the c.html:

<iframe id= "c_iframe" height= "0" width= "0" src= "http://www.a.com/agent.html" style= "Display:none" ></iframe >
<script type= "Text/javascript" >
(function Autoheight () {
var b_width = Math.max (document.body.scrollwidth,document.body.clientwidth);
var b_height = Math.max (document.body.scrollheight,document.body.clientheight);
var c_iframe = document.getElementById ("C_iframe");
C_IFRAME.SRC = c_iframe.src + "#" + b_width + "|" + b_height; Here through the hash pass the b.htm
})();
</script>

Finally, put a paragraph of JS in the agent.html:

<script type= "Text/javascript" >
var b_iframe = window.parent.parent.document.getElementById ("iframe");
var hash_url = Window.location.hash;
if (Hash_url.indexof ("#") >=0) {
var hash_width = Hash_url.split ("#") [1].split ("|") [0]+ "px";
var hash_height = Hash_url.split ("#") [1].split ("|") [1]+ "px";
B_iframe.style.width = Hash_width;
B_iframe.style.height = Hash_height;
}
</script>
Agent.html Gets the width and height values from the URL and sets the height and width of the IFRAME (because agent.html is under www.a.com, so it is not subject to JavaScript's homology restrictions when manipulating a.html)

Note that this article discusses the IFRAME adaptive and the previous article of the IFRAME Operation DOM is based on the same domain operation, that is, under the same domain name implementation, then if the different domain names that cross domain is not the operation. About IFRAME cross-domain operations related introduction Please pay attention to the next installment of the article introduction

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.