SoFunction
Updated on 2025-04-07

JavaScript dynamically changes the height of IFrame to achieve automatic stretching

Dynamically change the height of the IFrame, realize the automatic expansion of the IFrame, and the parent page will also automatically shrink.
Principle: When the IFrame child page is loaded, the parent IFrame object is called and its height is changed.
Specific implementation 1:
1. Add JavaScript to the specific page of IFrame (that is, subpages).
Copy the codeThe code is as follows:

<script>
function IFrameResize(){
//alert(); //The height of the current page pops up
var obj = ("childFrame"); //Get parent page IFrame object
//alert(); //The height set in the IFrame in the parent page is popped up
= ; //Adjust the height of the IFrame in the parent page to the height of this page
}
</script>

2. Add the onload event to the body of the specific page of the IFrame (that is, the subpage).
Copy the codeThe code is as follows:

<body onload="IFrameResize()">

3. Add ID to the IFrame tag of the parent page, that is, the childFrame written in the second line in the method body in the first step above
Copy the codeThe code is as follows:

<IFRAME border=0 marginWidth=0
frameSpacing=0 marginHeight=0
src="" frameBorder=0
noResize scrolling="no" width=100% height=100% vspale="0" ></IFRAME>

Specific implementation 2:
Copy the codeThe code is as follows:

//Dynamic change of the height of the parent class iframe
//JS called by iframe page
$(function(){
//Get the height of the window
var winH = $(window).height();
//Get the height of the page
var bodyH = $(document).height();
if(bodyH > winH){
("mainFrame").height=bodyH;
}else{
("mainFrame").height=winH;
}
});

The parent page's iframe is
Copy the codeThe code is as follows:

<iframe src="" height="700" frameborder="0" width="100%" name="mainFrame"></iframe>