Summary of the classic iframe adaptive height method

Source: Internet
Author: User

Iframe highly adaptive

Iframe highly adaptive is a very old topic. Although html5 has abandoned the frame framework, the iframe label still exists. If you do not know the differences between frame and iframe, you can refer to my previous article: Introduction to the iframe and frame attributes of the html framework and frameset.

Although iframe is rarely used in projects, iframe is still used in some projects. Iframe was used in a recent case.

The basic case is as follows: because the mobile browser does not preview PDF well, you can change the preview PDF on your mobile phone to preview html. Because PDF is generated in html. A 10-page PDF is displayed in 10 html files to achieve a similar effect. You must use multiple iframe to preview these html pages.

Problem: the iframe must be highly adaptive and looks like a PDF. Therefore, I would like to repeat the question of iframe adaptive height.

Ideas

1. Add an overlay layer on the surface of the preview PDF (in fact, html preview. Prompt PDF loading ....
2. Obtain the height of each Iframe page and assign the height to Iframe.
3. When the window. onload time is over, we will hide the animation "The PDF file is loading. [For details about the load event, refer]

4. At this time, the height of Iframe has been self-adaptive, and it looks like previewing a PDF.

The highly adaptive code is as follows:

<Iframe src = "test 2.html" width = "100%" height = "600" id = "iframe1" onload = "iFrameHeight ('iframe1 ') "name =" iframe1 "> </iframe>
<Iframe src = "test 2.html" id = "iframe2" onload = "iFrameHeight ('iframe2')" name = "iframe2"> </iframe>
<Iframe src = "test 2.html" id = "iframe3" onload = "iFrameHeight ('iframe3')" name = "iframe3"> </iframe>
<Iframe src = "test 2.html" id = "iframe4" onload = "iFrameHeight ('iframe4')" name = "iframe4"> </iframe>
</Body>
<Script>
Console. log (document. getElementById ("iframe3"). contentWindow );
Function iFrameHeight (id ){
Var ifm = document. getElementById (id );
Var subWeb = document. frames? Document.frames[id).doc ument: ifm. contentDocument;
If (ifm! = Null & subWeb! = Null ){
Ifm. height = subWeb. body. scrollHeight;
    }
}
</Script>

Test 2.html is the pdf page you want to preview. It can be very long!

Note:

1. The above code must be previewed in the localhost and other server environments
2. The src of test 2.html, that is, iframe, must be in the same domain
Code explanation

Document. getElementById ("iframe3"). contentWindow can be used to obtain the window object of iframe.

Google Explorer can use

Document.frames[id).doc ument get the document object

Supported by Firefox. ie over ie8 can use

Document. getElementById (id). contentDocument to obtain the document object.

About document. body. scrollHeight and scrollHeight of a div, as well as detailed descriptions of various width and height, you can see my js/jquery wide and high understanding and application. This is the video I recorded on MOOC last year, however, it is still in scheduling .... (MOOC online is too slow ).

Other explanations

In fact, there are many ways to operate iframe! For example, jquery has a contents () method. You can find an id or segment in iframe.

For example:

$ ("# Iframe2 "). contents (). find ("someID" ).html () or $ ("# mainiframe "). contains (). find ("someID "). text ()

Iframe2 contains an ID.

You can also mix Javascript and jquery! For example:

$ (Window. frames ["iframe1" cmd.doc ument). find ("input [@ type = 'Radio ']"). attr ("checked", "true ");

Set all radio selections in iframe1.

Examples

The iframe content is unknown and highly predictable

At this time, we can add a default CSS min-height value, and then use javascript to change the height. Common compatible codes include:


// Document. domain = "caibaojian.com ";
Function setIframeHeight (iframe ){
If (iframe ){
Var iframeWin = iframe. contentWindow | iframe. contentDocument. parentWindow;
If (iframeWin.doc ument. body ){
Iframe. height = iframeWin.document.doc umentElement. scrollHeight | iframeWin.doc ument. body. scrollHeight;
}
}
};

Window. onload = function (){
SetIframeHeight (document. getElementById ('external-framework '));
};


You only need to modify the above iframe ID. Or you can write code directly in iframe. We recommend that you use the above code to avoid html code contamination.

<Iframe src = "backtop.html" frameborder = "0" scrolling = "no" id = "external-frame" onload = "setIframeHeight (this)"> </iframe>

Multiple iframe

<Script language = "javascript">
// Enter the list of iframe names that you want to automatically adjust the height based on the page height
// Use commas (,) to separate the IDs of each iframe. For example, ["myframe1", "myframe2"] can have only one form.
// Define the iframe ID
Var iframeids = ["test"];
// If your browser does not support iframe, whether to hide iframe: yes, no
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 your browser is NetScape
Dyniframe [I]. height = dyniframe [I]. contentDocument. body. offsetHeight;
Else if (dyniframe [I]. Document & dyniframe [I]. Document. body. scrollHeight) // if your browser is IE
Dyniframe [I]. height = dyniframe [I]. Document. body. scrollHeight;
}
}
// Display the browser that does not support iframe based on the set parameters
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>


Call the ID of a known iframe

Function iframeAutoFit (iframeObj ){
SetTimeout (function () {if (! IframeObj) return; iframeObj. height = (iframeObj. Document? IframeObj. Document. body. scrollHeight: iframeObj. contentDocument. body. offsetHeight) ;}, 200)
}


Iframe height adaptive for content width variation

<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.content20.doc ument. body. scrollHeight;
Var dHeight = iframe.content?document.doc umentElement. 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 and you will see the run.
Cross-Origin iframe adaptive height

During cross-origin, js in the parent page cannot obtain the height of the iframe page due to the same-origin policy of js. A page is required for proxy.
The method is as follows: assume that a page a.html under www.a.comshould include a page c.html under www. B .com.
We use another page agent.html under www.a.comas a proxy to get the height of the iframe page and set the height of the iframe element.

A.html contains iframe:

<Iframe src = "http://www. B .com/c.html" id = "Iframe" frameborder = "0" scrolling = "no" style = "border: 0px;"> </iframe>

Add the following code to 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; // pass through hashto B .htm width and height.
})();
</Script>

Put the following JavaScript code in agent.html:

<Script type = "text/javascript">
Var B _iframe = response parent.parent.doc ument. 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>

The same source code of JavaScript is not restricted during callback)

Summary

Summary of iframe: The above is the iframe used in this project. I suddenly thought of some incomplete points. Please give me more advice!

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.