【问题标题】:Get size of inline iframe获取内联 iframe 的大小
【发布时间】:2018-11-01 13:33:17
【问题描述】:

我有一个 iframe 内联 src,例如:

let src = `data:text/html;charset=UTF-8,<html>
    <body>
      <p>Content</p>
    </body>
  </html>`

当页面加载时,我正在创建 iframe 并将其添加到页面正文:

let iframe = document.createElement("iframe")
document.querySelector('body').appendChild(iframe)

然后我将 src 设置为 iframe:

iframe.setAttribute('src', src)

如何获取 iframe 内容中呈现的宽度和高度并将其设置为 iframe 宽度和高度以及执行此操作的最佳方法是什么(使用 JS 或可能使用 CSS)

【问题讨论】:

  • 使用 iframe 而不是 div 的目的是什么?跨域浏览器政策让这种事情头疼
  • 可以获取iframe变量的innerHeight & innerWidth。
  • @dano,这是因为在那个 iframe 中实际上应该是电子邮件 html,它不应该依赖于其他样式。

标签: javascript html css iframe


【解决方案1】:

我不确定您要达到什么目的,因此我将仅回答有关获取元素比例并根据另一个元素相应地更改它们的部分问题。

实现这一点最简单的方法可能是使用 jQuery

$(function(){
  
  $('#changed').css({'height': $('#whatfrom').height(), 'width': $('#whatfrom').width()});  

});
#changed {
   height: 50px;
   width: 50px;
   outline: 1px solid red;
}

#whatfrom {
   margin-top: 10px;
   height: 150px;
   width: 100px;
   outline: 1px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="changed">I'll take width and height of the div below me</div>
<div id="whatfrom">Watch.. the element above will take my width and height. What a copycat!</div>

显然将 #changed#whatfrom div 更改为您需要的任何内容

【讨论】:

    【解决方案2】:

    我所做的是将about:blank 用作src,这样您就可以轻松地从页面访问iframe,而不会遇到“同源策略” 问题

    let html = `<p>Content</p>`;
    
    let iframe = document.createElement("iframe")
    document.body.appendChild(iframe);    
    
    iframe.src = 'about:blank';
    
    iframe.onload = function(){
      let win = this.contentWindow; 
      win.document.write(html);  
      console.log('inner width of iframe window=', win.innerWidth);  
    }
    

    JSFiddle DEMO

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-05-02
      • 2013-07-26
      • 2015-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-02
      相关资源
      最近更新 更多