【问题标题】:Automatically resize iframes with srcdoc attribute使用 srcdoc 属性自动调整 iframe 的大小
【发布时间】:2020-03-09 12:47:46
【问题描述】:

我正在尝试使用带有 srcdoc 属性的 iframe 元素在页面上显示电子邮件。

目前我正在使用此代码来调整 iframe 的大小。

$(document).ready(function() {
  $('iframe').each(function(index, el) {
    el.onload = function() {
      el.style.height = el.contentWindow.document.body.scrollHeight + 'px';
    }
  })
});

但它并不总是有效。有时内容会正确调整大小,有时则不会。

我见过像https://medium.com/better-programming/how-to-automatically-resize-an-iframe-7be6bfbb1214 这样的解决方案,但据我所知,这需要我在 srcdoc 内容中注入一些 js,然后监听 window.onmessage 事件。我觉得这是一个麻烦的解决方案。这是唯一的解决方案,还是有更好的方法来处理这个问题?

【问题讨论】:

  • 其中一些 iframe 可能此时已经完成“加载”其内容,因此您尝试添加加载处理程序现在,对他们来说只是迟到了。可能可以通过此时检查 iframe 内文档的readyState 来解决 - 如果这表明complete,那么您应该能够立即读取正确的大小,并且不需要再添加负载处理程序。

标签: javascript jquery html iframe


【解决方案1】:

通过使用 CBroe 提到的 readystate,我能够获得可靠的结果。

$('iframe').each(function(index, el) {
  $(el).ready(function(){
    el.style.height = el.contentWindow.document.body.scrollHeight + 'px';
  });
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-27
    • 1970-01-01
    • 2011-04-26
    • 1970-01-01
    • 2019-09-14
    相关资源
    最近更新 更多