首页 > 解决方案 > src 为 base64 编码时如何获取 iframe 内容高度?

问题描述

这是我想动态显示内容的 iframe。

<iframe onload='resize()' id='ifr' src='data:text/html;charset=utf-8;base64,Encoded text here' width=100% height=400px></iframe>

我试过这样的东西..但高度总是返回 0

function resize() {
   $('#ifr').height($('#ifr').contents().height());
}

这是jsfiddle ..

https://jsfiddle.net/zetapark/rajz6sy5/1/

标签: javascripthtmliframebase64height

解决方案


$('iframe') 为您提供文档中的所有 iframe,因此您应该为框架提供 id 并像 $('#MYiframe') 一样使用它,或者从 jquert 返回的内容中获取第一个元素。

function resize() {
   $('iframe')[0].height($('iframe')[0].contents().height());
}

而且我还在 SO 上找到了用于调整内容的 iframe 的大小。

iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
iFrame.height = iFrame.contentWindow.document.body.scrollHeight;

推荐阅读