Resize iframe height according to content height i

2019-01-03 13:20发布

I am opening my blog page in my website. The problem is I can give a width to an iframe but the height should be dynamic so that there is no scrollbar in the iframe, and it looks like a single page...

I have tried various JavaScript code to calculate the height of the content but all of them give an access denied permission error and is of no use.

<iframe src="http://bagtheplanet.blogspot.com/" name="ifrm" id="ifrm" width="1024px" ></iframe>

Can we use Ajax to calculate height or maybe using PHP?

10条回答
霸刀☆藐视天下
2楼-- · 2019-01-03 14:00

Try using scrolling=no attribute on the iframe tag. Mozilla also has an overflow-x and overflow-y CSS property you may look into.

In terms of the height, you could also try height=100% on the iframe tag.

查看更多
欢心
3楼-- · 2019-01-03 14:01

You can do this with JavaScript.

document.getElementById('foo').height = document.getElementById('foo').contentWindow.document.body.scrollHeight + "px";
查看更多
在下西门庆
4楼-- · 2019-01-03 14:03

The trick is to acquire all the necessary iframe events from an external script. For instance, you have a script which creates the iFrame using document.createElement; in this same script you temporarily have access to the contents of the iFrame.

var dFrame = document.createElement("iframe");
dFrame.src = "http://www.example.com";
// Acquire onload and resize the iframe
dFrame.onload = function()
{
    // Setting the content window's resize function tells us when we've changed the height of the internal document
    // It also only needs to do what onload does, so just have it call onload
    dFrame.contentWindow.onresize = function() { dFrame.onload() };
    dFrame.style.height = dFrame.contentWindow.document.body.scrollHeight + "px";
}
window.onresize = function() {
    dFrame.onload();
}

This works because dFrame stays in scope in those functions, giving you access to the external iFrame element from within the scope of the frame, allowing you to see the actual document height and expand it as necessary. This example will work in firefox but nowhere else; I could give you the workarounds, but you can figure out the rest ;)

查看更多
看我几分像从前
5楼-- · 2019-01-03 14:05

@SchizoDuckie's answer is very elegant and lightweight, but due to Webkit's lack of implementation for scrollHeight (see here), does not work on Webkit-based browsers (Safari, Chrome, various and sundry mobile platforms).

For this basic idea to work on Webkit along with Gecko and Trident browsers, one need only replace

<body onload='parent.resizeIframe(document.body.scrollHeight)'>

with

<body onload='parent.resizeIframe(document.body.offsetHeight)'>

So long as everything is on the same domain, this works quite well.

查看更多
登录 后发表回答