to fit iframe to its content height

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-18 05:21:40

问题


        <script language="JavaScript">
        function autoResize(id){
            alert('check');
            var newheight;
            var newwidth;

            if(document.getElementById){
                newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
                newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
            }
            alert(newheight);
            alert(newwidth);
            document.getElementById(id).height= (newheight) + "px";
            document.getElementById(id).width= (newwidth) + "px";
        }
        </script>

HTML:

            <iframe id="faq_iframe" src="http://www.google.com" width="100%" height="200px" scrolling="no" frameborder="0" marginheight="0" onload="javascript: autoResize('faq_iframe');"></iframe>

Question: I am using iframe to display my page. i need to fit iframe to my page height how can i do this.

I had tried above codes

i got this error via firebug

Permission denied for <http://localhost> to get property Window.document from <http://www.google.co.in>.
[Break On This Error] newheight=document.getEleme...tWindow.document.body.scrollHeight; 

How to make iframe to fit its height to height of my page given in iframe src


回答1:


In your case you can't.

It is not possible for an iframe with content that lives on one domain, to read any properties, including width and height, on the document it is injected into if this document lives on another domain.

There are several ways to achieve cross domain communication across iframes but it involves the document that the iframe lives in is a willing participant, with active javascript to facilitate it.




回答2:


You can't retrieve the iframe's height, because of Cross-domain policy. Create server-side proxy for this purpose.




回答3:


function autoResize(id){
   moz=document.getElementById&&!document.all
   mozHeightOffset=20
   document.getElementById(id).height=window.frames[id].document.body.scrollHeight+(moz?mozHeightOffset:0);
}

This code will adjust iframe's height according to it's content. call this function onload of iframe.




回答4:


I've been struggling with this as well. I eventually ended up using postMessage (HTML5). Check out an example here: cross-domain iframe resizer?




回答5:


Try this, you can change for even when you want. this example use jQuery.

$('#iframe').live('mousemove', function (event) {

var theFrame = $(this, parent.document.body);

this.height($(document.body).height() - 350);
});



来源:https://stackoverflow.com/questions/4724499/to-fit-iframe-to-its-content-height

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!