javascript resize iframe height dynamically issue
I'm having an issue resizing an iframe to fit the content located within the frame'd page. I used a suggestion I found here to resi开发者_运维技巧ze the frame dynamically.
In my frame'd pages I have
<body onload='parent.resizeIframe(getDocHeight())'>
function getDocHeight() {
var D = document;
alert(D.URL);
return Math.max(
Math.max(D.body.scrollHeight, D.documentElement.scrollHeight),
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
Math.max(D.body.clientHeight, D.documentElement.clientHeight)
);
}
And in the page containing the iframe I have this
function resizeIframe(newHeight) {
var showsFrame = document.getElementById('frm');
showsFrame.style.height = parseInt(newHeight) +'px';
}
The function is getting called correctly by each frame'd page, but for some reason the 'newHeight' parameter being passed is keeping the largest height value. For example if I have 2 frame'd pages one with a scroll height of 300px and the other with 500px. When I first click my link to load the 300px page it works fine, but if I click the link to the 500px page and then try and come back to the 300px page, the value of 'newHeight' remains at 500. Any ideas? TIA
I found the issue I was having for anyone else that is experiencing the same thing. Because my frame'd pages didn't have much content the scrollHeight was reporting the length of the entire document and not cutting where my content stopped. Instead of trying to calculate scrollHeight, I simply looked for the offsetHeight which was the correct height I was looking for. Firebug is a nice tool to inspect the DOM of each page and see the values of each attribute without having to write debugging messages. I put this line in every frame'd page
<body onload='parent.resizeIframe(getDocHeight())'>
and in a separate js file I have this code to calculate the height.
function getDocHeight() {
var D = document;
return Math.max(
Math.max(D.body.offsetHeight, D.documentElement.offsetHeight),
);
Try it with JQuery
function resizeIframe(newHeight) {
$('#iframeId').attr('height',newHeight);
or
$("#frameId").height(newHeight);
}
精彩评论