首页 > 解决方案 > jQuery:Bootstrap 模式中的 100% 高度 iframe

问题描述

我有一个生成要打印的文档的 php 脚本。我正在尝试将此脚本以 100% 的宽度和高度放入 bootstrap 4 模式,以便客户端可以检查内容然后将其打印出来。

<button type="button" id="print_modal" class="btn btn-primary" data-toggle="modal" data-target="#printmodal">Result</button>
<div class="modal fade" id="printmodal">
    <div class="modal-dialog" style="max-width:210mm !important">
        <div class="modal-content">
          <div class="modal-header">
            <button class="btn btn-primary ml-1" id="print_btn">Tisk</button>
            <button type="button" class="close" data-dismiss="modal">&times;</button>
          </div>
          <div class="modal-body text-left" id="print_content">
            <!-- IFRAME HERE -->
          </div>
        </div>
    </div>
</div>

我首先将 iframe 放入模态,何时填充(出于性能推理 - 有时它是一个非常长的文档) - 这是有效的

$('#print_modal').click(function () {
  $('#print_content').html('<iframe src="./index.php?print" frameborder="0" scrolling="no" id="print_frame"></iframe>');
});

比我需要在 iframe 元素上设置 100% 的高度。问题是以下 jquery 脚本返回 0 高度。可能是因为默认隐藏在模态中。

$("#print_frame").on("load", function () {
  $(this).height($(this).contents().find("html").height());
});

我需要类似超时的东西来检查 iframe 填充后的高度,但我不知道如何。

不工作:

在生成的 iframe 上使用 onload 参数:(返回 0px - modal FadeIn 可能比 iframe append 慢...)

<iframe src="./index.php?print" onload="ifrhgh()">

function ifrhgh(){
   var iframehght =  $("#print_frame").contents().height();
}

标签: jqueryiframebootstrap-4bootstrap-modal

解决方案


已解决: 关键是在shown.bs.modal(成功加载后由模态触发的 BS4 事件)上创建 iframe 然后 onload 参数调用ifrhgh()函数将 iframe 设置为等于内容

$(function () {
    $('#printmodal').on('shown.bs.modal', function () {
        $('#print_content').html('<iframe width="100%" onload="ifrhgh()" src="./index.php?print" frameborder="0" scrolling="no" id="print_frame"></iframe>');
    });
});

function ifrhgh(){
    var iframehght =  $("#print_frame").contents().height();
    $("#print_frame").height(iframehght);
}

推荐阅读