javascript - 通过 JavaScript 调整 iFrame 内容大小

标签 javascript jquery html iframe

我想知道是否有某种方法可以做到这一点,以便如果 iFrame 中有一堆内容,它只会调整文档的大小以使其适合。使 iFrame 内的所有内容变小。澄清一下,我想调整内容的大小,而不是 iFrame 本身的大小。

我有什么想法可以做到这一点吗?

我尝试过一些东西,但到目前为止还没有成功。

脚本:

<script type="text/javascript">
function autoResize(id){
    var newheight;
    var newwidth;

    if(document.getElementById){
        newheight=document.getElementById(id).contentWindow.document .body.scrollHeight;
        newwidth=document.getElementById(id).contentWindow.document .body.scrollWidth;
    }

    document.getElementById(id).height= (newheight) + "px";
    document.getElementById(id).width= (newwidth) + "px";
}
</script>

iFrame:

<iframe id="iframehtml" style="width:100%;height:100%;" onLoad="autoResize('iframe1');"></iframe>

顺便说一句,没有为 iFrame 设置 src 的原因是因为我在 JavaScript 中有它,所以当您单击按钮时,它将通过 jQuery 编辑 iFrame 的 html。

最佳答案

您可以使用加载事件来调整 iframe 的大小

var iframe = document.getElementByID('your-iframe');
iframe.addEventListener('load', function() {
  iframe.style.height = iframe.contentWindow.document.body.offsetHeight + 'px';
})

关于javascript - 通过 JavaScript 调整 iFrame 内容大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19779792/

相关文章:

JavaScript:IE 11 和 MS Edge 覆盖 CTRL+P

javascript - 无法从 javaScript 调用 Bootstrap 插件

javascript - 无法加载资源错误 : the server responded with a status of 404(not found)

javascript - 如何将数据添加到 SlickGrid DataView?

javascript - 有没有一种方法可以根据不同页面的样式表更改页面的样式表?

javascript - 如何通过 .xyz.com/#divname 访问我的网站,有人可以帮助我吗?

javascript - Fabricjs svg解析错误

javascript - 如何使用meteor将三个js代码放入单独的JS文件中

javascript - jQuery 选择复选框

html - XPath选择不只有一个特定子节点的节点?