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

CLi*_*own 12 html javascript iframe

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

我需要的是能够从iframe中检测iframe的宽度和高度,所以如果iframe srciframeContent.html我需要能够在这个页面上显示值.

我无法控制仅托管iframe的页面iframe的内容.

这可能吗?

Ten*_*eff 12

您始终可以获取网页维度,无论页面是在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 );
}
Run Code Online (Sandbox Code Playgroud)

  • 您真的应该提供一个指向您复制和粘贴答案的链接.这样就可以给予应有的信用.此外,我认为在这个时代编写代码时我们可以安全地忘记IE 4. (4认同)

Sim*_*one 3

如今这很简单:

<script>
  console.log(innerWidth, innerHeight)
</script>
Run Code Online (Sandbox Code Playgroud)

只需确保从 iframe 中加载此 JavaScript,它将在浏览器控制台中打印 iframe 窗口的宽度和高度。