Javascript 从 iframe 内部检测 <iframe> 的高度和宽度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7808729/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:40:57  来源:igfitidea点击:

Detect <iframe> height and width from inside the iframe

javascripthtmliframe

提问by CLiown

I doubt this is actually possible but Im prepared to be corrected.

我怀疑这实际上是可能的,但我准备纠正。

What I need is to be able to detect the width and height of an iframe from within the iframe, so if the iframe srcis iframeContent.htmlI need to be able to surface the values on this page.

我需要的是能够从 iframe 中检测 iframe 的宽度和高度,因此如果 iframesrciframeContent.html我需要能够显示此页面上的值。

I have no control over the page that hosts the iframe only the contents of the iframe.

我无法控制承载 iframe 的页面,只能控制 iframe 的内容。

Is this possible?

这可能吗?

采纳答案by Teneff

You can always get the web page dimensions, no matter if the page is loaded inside an iframeor a new window it always works the same way. This is a function I've found used to get windowdimensions, you can also use it to get an <iframe>dimensions.

您始终可以获取网页尺寸,无论页面是在iframe窗口内还是在新窗口中加载,它始终以相同的方式工作。这是我发现用于获取window尺寸的函数,您也可以使用它来获取<iframe>尺寸。

function alertSize() {
  var myWidth = 0, myHeight = 0;
  if( typeof( window.innerWidth ) == 'number' ) {
    //Non-IE
    myWidth = window.innerWidth;
    myHeight = window.innerHeight;
  } else if( document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) {
    //IE 6+ in 'standards compliant mode'
    myWidth = document.documentElement.clientWidth;
    myHeight = document.documentElement.clientHeight;
  } else if( document.body && ( document.body.clientWidth || document.body.clientHeight ) ) {
    //IE 4 compatible
    myWidth = document.body.clientWidth;
    myHeight = document.body.clientHeight;
  }
  window.alert( 'Width = ' + myWidth );
  window.alert( 'Height = ' + myHeight );
}