前端开发中,我们往往需要处理iframe,可能有的时候希望iframe根据内容自适应高度以便不出现令人烦心的滚动条,下面这段代码可以帮助你实现类似功能。
$(document).ready(function() { // Set specific variable to represent all iframe tags. var iFrames = document.getElementsByTagName('iframe'); // Resize heights. function iResize() { // Iterate through all iframes in the page. for (var i = 0, j = iFrames.length; i < j; i++) { // Set inline style to equal the body height of the iframed content. iFrames[i].style.height = iFrames[i].contentWindow.document.body.offsetHeight + 'px'; } } // Check if browser is Safari or Opera. if ($.browser.safari || $.browser.opera) { // Start timer when loaded. $('iframe').load(function() { setTimeout(iResize, 0); } ); // Safari and Opera need a kick-start. for (var i = 0, j = iFrames.length; i < j; i++) { var iSource = iFrames[i].src; iFrames[i].src=""; iFrames[i].src = iSource; } } else { // For other good browsers. $('iframe').load(function() { // Set inline style to equal the body height of the iframed content. this.style.height = this.contentWindow.document.body.offsetHeight + 'px'; } ); } } );
文章来源:http://bbs.html5cn.org/forum.php?mod=viewthread&tid=11622&extra=