根据内容高度调整iframe高度

4
我正在尝试根据iframe内容(网页)的高度和宽度来调整其大小。我使用了在Stack Overflow上找到的代码。对于新宽度的设置,似乎可以工作,但我无法让高度起作用,而且我不知道原因。
您可以在此处查看并编辑我的示例:http://jsfiddle.net/dzorz/pvtr3/ 以下是我的HTML:
<iframe id="finance-iframe" class="finance-iframe" src="http://wordpress.org" width="100%" height="300px" marginheight="0" frameborder="0" onLoad="autoResize('finance-iframe');"></iframe>

以及 JavaScript:

function autoResize("finance-iframe"){
  var newheight;
  var newwidth;

  if(document.getElementById){
    newheight=document.getElementById("finance-iframe").contentWindow.document.body.scrollHeight;
    newwidth=document.getElementById("finance-iframe").contentWindow.document.body.scrollWidth;
  }

  document.getElementById("finance-iframe").height= (newheight) + "px";
  document.getElementById("finance-iframe").width= (newwidth) + "px";
}

我做错了什么?


解决方案已经在这里找到了:https://dev59.com/Smkw5IYBdhLWcg3wUI_x - Scalpweb
2个回答

8

查看iFrame内容的高度有四个不同的属性。

document.documentElement.scrollHeight
document.documentElement.offsetHeight
document.body.scrollHeight
document.body.offsetHeight

遗憾的是,它们都可能给出不同的答案,并且在不同的浏览器之间不一致。如果将body边距设置为0,则document.body.offsetHeight提供最佳答案。要获取正确的值,请尝试使用此函数;该函数取自iframe-resizer库,该库还负责在内容更改或浏览器调整大小时保持iFrame的正确大小。

function getIFrameHeight(){
    function getComputedBodyStyle(prop) {
        function getPixelValue(value) {
            var PIXEL = /^\d+(px)?$/i;

            if (PIXEL.test(value)) {
                return parseInt(value,base);
            }

            var 
                style = el.style.left,
                runtimeStyle = el.runtimeStyle.left;

            el.runtimeStyle.left = el.currentStyle.left;
            el.style.left = value || 0;
            value = el.style.pixelLeft;
            el.style.left = style;
            el.runtimeStyle.left = runtimeStyle;

            return value;
        }

        var 
            el = document.body,
            retVal = 0;

        if (document.defaultView && document.defaultView.getComputedStyle) {
            retVal =  document.defaultView.getComputedStyle(el, null)[prop];
        } else {//IE8 & below
            retVal =  getPixelValue(el.currentStyle[prop]);
        } 

        return parseInt(retVal,10);
    }

    return document.body.offsetHeight +
        getComputedBodyStyle('marginTop') +
        getComputedBodyStyle('marginBottom');
}

6
<section id="about" data-type="background" data-speed="10" class="pages">
    <iframe src="index.html" id="demo_frame" align="center" scrolling="no"  frameborder="0" marginheight="0" marginwidth="0"></iframe>
</section>

<script>
        $('iframe').load(function() {
            this.style.height = this.contentWindow.document.body.offsetHeight + 'px';
        });
</script>

2
这应该是正确的答案。它是最优雅的。 - Moe
在我的情况下不起作用。 - Sin Hasegawa

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