【问题标题】:Detect <iframe> height and width from inside the iframe从 iframe 内部检测 <iframe> 的高度和宽度
【发布时间】:2011-12-10 03:48:46
【问题描述】:

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

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

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

这可能吗?

【问题讨论】:

    标签: javascript html iframe


    【解决方案1】:

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

    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 );
    }
    

    【讨论】:

    • 您确实应该提供一个链接,指向您复制和粘贴答案的位置。这样就可以在到期时给予信用。另外,我认为在这个时代编写代码时我们可以放心地忘记 IE 4。
    • window.innerWidth/Height 报告 IFRAME 的大小,而不是浏览器(例如,如果浏览器窗口的大小调整为小于包含 IFRAME 的大小,浏览器总是报告 IFRAME 的大小)
    【解决方案2】:

    现在这很简单:

    <script>
      console.log(innerWidth, innerHeight)
    </script>
    

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

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 2013-08-17
      • 1970-01-01
      • 1970-01-01
      • 2021-03-16
      • 2016-09-11
      • 1970-01-01
      • 2013-11-22
      • 1970-01-01
      相关资源
      最近更新 更多