Dynamically adjust the height of an iframe with JavaScript

Source: Internet
Author: User
Javascript| News

  Keywords: javascript, iframe, height, Firefox

When you use an IFRAME on the page, you generally do not want the IFRAME to display unsightly scroll bars so that the contents of the IFRAME and the contents of the main page are seamless. At this point you will set the scrolling= "no" attribute. However, if the content of the IFRAME is changed, the height will change with the content changes, your iframe will appear too long to cause a large amount of blank, or just the opposite, because the height of the IFRAME is too small to cause a part of the content will be blocked. Here I provide a compatible ie/ns/firefox JavaScript script that dynamically adjusts the height of the iframe. If you need to adjust the width, the principle is the same, this article is not detailed.

First, you must include the following JavaScript code on your home page:

<script language= "Javascript" >
var getffversion=navigator.useragent.substring (navigator.userAgent.indexOf ("Firefox")). Split ("/") [1]
Extra height in px to add to IFRAME in FireFox 1.0+ browsers
var ffextraheight=getffversion>=0.1? 16:0

function Dyniframesize (iframename) {
var ptar = null;
if (document.getElementById) {
Ptar = document.getElementById (iframename);
}
else{
Eval (' Ptar = ' + Iframename + '; ');
}
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+ffextraheight;
}
else if (ptar.document && pTar.Document.body.scrollHeight) {
ie5+ syntax
Ptar.height = PTar.Document.body.scrollHeight;
}
}
}
</script>

Then add the code where the main page uses the IFRAME:

<iframe id= "Mytestframeid"
Marginwidth=0 marginheight=0 frameborder=0 scrolling=no src= "address and name of the page to embed" width=200 height=100></iframe>



Related Article

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.