获得iframe的高度

时间:2013-09-12 13:27:09

标签: javascript jquery html iframe

我正在构建一个内容为iframe的对话框。当对话框打开时,我有以下代码,我试图让这项工作从各种来源中提取:

var iframeDOM = document.createElement("IFRAME"); 
iframeDOM.setAttribute("frameborder", "0"); 
iframeDOM.setAttribute("scrolling", plugin.settings.scrolling ? "" : "no"); 
iframeDOM.setAttribute("allowtransparency", isIE ? "true" : ""); 



var setDimensions = function(){
                        console.log("load");
                        var iframeWin = iframeDOM.contentWindow || iframeDOM.contentDocument.parentWindow;
                        if (iframeWin.document.body) {
                            console.log("new height: " + iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight); //Not giving real height, always 0
                            console.log("new client height: " + iframeWin.document.documentElement.clientHeight); 
                            iframeDOM.height = 550;
                            iframeDOM.width  = 550;
                        }

                    };

                    $(iframeDOM).load(setDimensions)
                                .appendTo($element.children().first())
                                .attr({ src: plugin.settings.href, name: new Date().getTime() });  

正如您所看到的,我正在尝试记录iFrame的高度,但它总是打印0(作为临时解决方法,我正在静态设置尺寸)

编辑:我更新此OP的另一个解决方案是返回错误:

 Error: Permission denied to access property 'document' if (iframeWin.document.body) {

2 个答案:

答案 0 :(得分:0)

iframe不会自动获取高度和宽度。您需要手动定义它,因此只能通过javascript捕获页面加载到iframe的实际高度,并将其指定为iframe的高度。但这种方法会造成不稳定。

更新

使用.height()函数计算页面高度并将其指定给iframe。它将以这种方式工作。

答案 1 :(得分:0)

这是我发现的非常好的东西。我认为它需要调整,但我对JavaScript并不擅长。

<script language="JavaScript">
<!--
function autoResize(id){
  var newheight;
  var newwidth;

if(document.getElementById){
    newheight=document.getElementById(id).contentWindow.document.body.scrollHeight;
    newwidth=document.getElementById(id).contentWindow.document.body.scrollWidth;
}

document.getElementById(id).height= (newheight) + "px";
document.getElementById(id).width= (newwidth) + "px";
}
//-->
</script>

<iframe name="content" src="http://my-domain.com/home.html" width="100%" height="200px" id="iframe1" marginheight="0" frameborder="0" onLoad="autoResize('iframe1');">
</iframe>
相关问题