如何调整此js生成的iframe的高度到内容?

时间:2019-03-22 13:25:19

标签: javascript html iframe

我正在尝试根据内容调整iframe的高度。 JavaScript将动态添加iframe,这意味着JavaScript还必须处理元素的属性:

let iframe = document.createElement("iframe");
iframe.src = "https://en.wikipedia.org/";

document.getElementById("foo").appendChild(iframe);

iframe.onload = function() {
  iframe.style.height = "600px";//<-- Does work, why?
  resizeIframe(iframe);//<-- Does not work
  //iframe.style.height = iframe.contentWindow.document.body.scrollHeight + "px"; //<-- Does not work (when uncommented)
}

function resizeIframe(obj) {
  obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
<div id="foo">
  <!-- Iframe to be inserted in here -->
</div>

JSFiddle

有人碰巧知道我可以做些什么吗?我找到了以下解决方案并将其应用于上面的代码:

function resizeIframe(obj) {
    obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}

Source

JavaScript函数可能(尽管在this example中不起作用)对于生成的<iframe>的纯HTML而言,当谈到JavaScript生成的<iframe>时,它似乎不起作用。我做错了什么还是应该使用其他替代方法?

编辑:我正在使用ASP.Net MVC,我的项目在视图中包含以下代码:

MyView.cshtml:

<div class="my-class text-center">
    <span>
        For testing purpose only, this elements has been added. Functionality:
    </span>
    <br />
    <button id="loadiframe" class="btn btn-lg btn-primary" data-toggle="modal" data-target=".bs-example-modal-lg">
        Load iframe
    </button>
</div>

单击该按钮时,应将iframe元素插入/添加到Bootstrap Modal.modal-content部分:

myscript.js:

function foobar() {
    let iframe = document.createElement("iframe");
    iframe.src = "/home";
    $(".modal .modal-content").html(iframe);
    iframe.onload = function () {
        iframe.style.height = iframe.contentWindow.document.body.scrollHeight + 'px';
    }
}

$(document).ready(function() {
    $("button#loadiframe").on("click", function () {
        foobar();
    });
});

这似乎确实添加了<iframe>,但没有调整高度。会有人碰巧知道我该如何解决这个问题?这一切都将在与我所指的“ home”控制器相同的域中发生,该控制器可在我的项目中找到并分配给我的<iframe>源属性(请参见上面的代码)。

0 个答案:

没有答案