iFrame根据内容高度调整大小仅适用于扩大吗?

3
请查看附加的CodePen示例,了解我所说的内容。尝试缩小浏览器窗口的宽度,框架应正确调整大小。然后最大化浏览器窗口,注意框架没有重新调整其高度。我有多个框架重叠在一起,所以这是一个相当烦人的问题。我已经尝试使用.height(),.outerHeight(),.innerHeight(),.scrollHeight和.clientHeight等方法,但都没有成功。 链接
var newHeight = $('#frame').contents().height();  
$('#frame').attr('height', newHeight);

感谢您提前给予的任何/所有帮助!

这是一个非常烦人的问题。我们过去使用了这个库来解决它:https://github.com/davidjbradshaw/iframe-resizer - 但你需要访问父页面和子页面。如果正确配置,即使通过跨域也可以很好地工作。我建议使用它。 - sauntimo
2个回答

1
尝试这个。
function resizeFrame() {
  var newHeight = $('#frame').contents().find("body").height();
  $('#frame').attr('height', newHeight + 20);
}

是的,那应该可行 - 但不幸的是,我不能依赖于标记中存在一个主体元素,这些框架将会显示。 - Craig Smith
所以假设它应该工作,但实际上并没有 - https://codepen.io/chavag/pen/YxypOQ - Chava Geldzahler
你没有添加 newHeight + 20,所以会出现滚动条。 - ewwink

0

试试这个

<script type="text/javascript">
var $ = jQuery.noConflict();
$(document).ready(function() {
    $(function($){
      var lastHeight = 0, curHeight = 0, $frame = $('iframe:eq(0)');
      setInterval(function(){
        curHeight = $frame.contents().find('body').height();
        if ( curHeight != lastHeight ) {
          $frame.css('height', (lastHeight = curHeight) + 'px' );
          $frame.css('border-width', 0 + 'px' );
        }
      },0);
    });
});


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接