To my knowledge, there isn't a very natural way of doing this, but there are some options.
setInterval()
You could use setInterval()
to repeatadly check the iframe's content height and adjust it if needed. This is simple, but inefficient.
Event Listeners
Any change of content in the iframe's content (and therefore height) is usually triggered by some event. Even if you're adding content from outside of the iframe, that "add" is probably triggered by a button click, for example. Here's something that might work for you: Live demo here (click).
var myIframe = document.getElementById('myIframe');
window.addEventListener('click', resizeIframe);
window.addEventListener('scroll', resizeIframe);
window.addEventListener('resize', resizeIframe);
myIframe.contentWindow.addEventListener('click', resizeIframe);
function resizeIframe() {
console.log('resize!');
}
Mutation Observer
This solution works in all up-to-date browsers - http://caniuse.com/mutationobserver
Live demo here (click).
It's really simple and should catch the relevant changes. If not, you could combine it with the event listener solution above to be sure things are updated!
var $myIframe = $('#myIframe');
var myIframe = $myIframe[0];
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
myIframe.addEventListener('load', function() {
setIframeHeight();
var target = myIframe.contentDocument.body;
var observer = new MutationObserver(function(mutations) {
setIframeHeight();
});
var config = {
attributes: true,
childList: true,
characterData: true,
subtree: true
};
observer.observe(target, config);
});
myIframe.src = 'iframe.html';
function setIframeHeight() {
$myIframe.height('auto');
var newHeight = $('html', myIframe.contentDocument).height();
$myIframe.height(newHeight);
}
Honorable mention to: overflow/underflow events.
Read about it here (there's A LOT to it).
and see my demo here (doesn't work in IE 11!).
This was a cool solution, but it's no longer working in IE. It might be possible to tweak it, but I'd rather use one of the above solutions, even if I had to fallback to a 1 second setInterval
for older browsers, just because it's a lot simpler than this solution.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…