调整iframe的宽度和高度以适应其中的内容

时间:2009-05-04 09:20:18

标签: javascript html iframe adjustment

我需要一个自动调整 width的{​​{1}}和height的解决方案,几乎不符合其内容。关键是在加载iframe后可以更改宽度和高度。我想我需要一个事件动作来处理iframe中包含的主体尺寸的变化。

31 个答案:

答案 0 :(得分:254)

<script type="application/javascript">

function resizeIFrameToFitContent( iFrame ) {

    iFrame.width  = iFrame.contentWindow.document.body.scrollWidth;
    iFrame.height = iFrame.contentWindow.document.body.scrollHeight;
}

window.addEventListener('DOMContentLoaded', function(e) {

    var iFrame = document.getElementById( 'iFrame1' );
    resizeIFrameToFitContent( iFrame );

    // or, to resize all iframes:
    var iframes = document.querySelectorAll("iframe");
    for( var i = 0; i < iframes.length; i++) {
        resizeIFrameToFitContent( iframes[i] );
    }
} );

</script>

<iframe src="usagelogs/default.aspx" id="iFrame1"></iframe>

答案 1 :(得分:44)

跨浏览器jQuery plug-in

跨界,跨域 library ,使用mutationObserver保持iFrame大小与内容相匹配,postMessage在iFrame和主页之间进行通信。无论是否使用jQuery都可以使用。

答案 2 :(得分:32)

到目前为止给出的所有解决方案仅考虑一次性调整大小。您提到您希望能够在修改内容后调整iFrame的大小。为了做到这一点,你需要在iFrame中执行一个函数(一旦内容被更改,你需要触发一个事件来说明内容已经改变了。)

我被困了一段时间,因为iFrame中的代码似乎仅限于iFrame中的DOM(并且无法编辑iFrame),并且在iFrame外部执行的代码被iFrame外部的DOM卡住了(并且无法接收来自iFrame内部的活动。

解决方案来自于发现(通过同事的帮助)可以告诉jQuery使用什么DOM。在这种情况下,父窗口的DOM。

因此,像这样的代码可以满足您的需求(在iFrame中运行时):

<script type="text/javascript">
    jQuery(document).ready(function () {
        jQuery("#IDofControlFiringResizeEvent").click(function () {
            var frame = $('#IDofiframeInMainWindow', window.parent.document);
            var height = jQuery("#IDofContainerInsideiFrame").height();
            frame.height(height + 15);
        });
    });
</script>

答案 3 :(得分:23)

用于嵌入的单线解决方案: 从最小尺寸开始并增加到内容大小。不需要脚本标签。

&#13;
&#13;
<iframe src="http://URL_HERE.html" onload='javascript:(function(o){o.style.height=o.contentWindow.document.body.scrollHeight+"px";}(this));' style="height:200px;width:100%;border:none;overflow:hidden;"></iframe>
&#13;
&#13;
&#13;

答案 4 :(得分:23)

如果iframe内容来自同一个域,那么这应该很有用。它确实需要jQuery。

$('#iframe_id').load(function () {
    $(this).height($(this).contents().height());
    $(this).width($(this).contents().width());
});

要让它动态调整大小,您可以这样做:

<script language="javaScript">
<!--
function autoResize(){
    $('#themeframe').height($('#themeframe').contents().height());
}
//-->
</script>
<iframe id="themeframe" onLoad="autoResize();" marginheight="0" frameborder="0" src="URL"></iframe>

然后在iframe加载的页面上添加:

<script language="javaScript">
function resize()
{
    window.parent.autoResize();
}

$(window).on('resize', resize);
</script>

答案 5 :(得分:15)

如果您不想使用jQuery,这是一个跨浏览器的解决方案:

/**
 * Resizes the given iFrame width so it fits its content
 * @param e The iframe to resize
 */
function resizeIframeWidth(e){
    // Set width of iframe according to its content
    if (e.Document && e.Document.body.scrollWidth) //ie5+ syntax
        e.width = e.contentWindow.document.body.scrollWidth;
    else if (e.contentDocument && e.contentDocument.body.scrollWidth) //ns6+ & opera syntax
        e.width = e.contentDocument.body.scrollWidth + 35;
    else (e.contentDocument && e.contentDocument.body.offsetWidth) //standards compliant syntax – ie8
        e.width = e.contentDocument.body.offsetWidth + 35;
}

答案 6 :(得分:8)

我正在使用此代码在页面上加载时自动调整所有iframe的高度(使用css auto Height)。经过测试,适用于IE,FF,Chrome,Safari和Opera。

function doIframe() {
    var $iframes = $("iframe.autoHeight"); 
    $iframes.each(function() {
        var iframe = this;
        $(iframe).load(function() {
            setHeight(iframe);
        });
    });
}

function setHeight(e) {
  e.height = e.contentWindow.document.body.scrollHeight + 35;
}

$(window).load(function() {
    doIframe();
});

答案 7 :(得分:6)

在我尝试了地球上的一切之后,这对我来说真的很有用。

的index.html

> node myClass.js

答案 8 :(得分:4)

这是一个可靠的解决方案

function resizer(id)
{

var doc=document.getElementById(id).contentWindow.document;
var body_ = doc.body, html_ = doc.documentElement;

var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight );
var width  = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );

document.getElementById(id).style.height=height;
document.getElementById(id).style.width=width;

}

html

<IFRAME SRC="blah.php" id="iframe1"  onLoad="resizer('iframe1');"></iframe>

答案 9 :(得分:3)

以下是几种方法:

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
</body>

和另一个替代

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="100%" width="100%"></iframe>
</body>

隐藏滚动,上面有两个替代方案

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;height:150%;width:150%" height="150%" width="150%"></iframe>
</body>

HACK WITH SECOND CODE

<body style="margin:0px;padding:0px;overflow:hidden">
    <iframe src="http://www.example.com" frameborder="0" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:150%;width:150%;position:absolute;top:0px;left:0px;right:0px;bottom:0px" height="150%" width="150%"></iframe>
</body>

要隐藏iFrame的滚动条,将父级设为“overflow:hidden”以隐藏滚动条,并使iFrame的宽度和高度达到150%,这会强制页面外的滚动条,因为body没有滚动条可能不会指望iframe超出页面的边界。这会以全宽隐藏iFrame的滚动条!

来源:设置iframe auto height

答案 10 :(得分:3)

我略微修改了Garnaph上面的伟大解决方案。似乎他的解决方案根据事件之前的大小修改了iframe大小。对于我的情况(通过iframe提交电子邮件)我需要在提交后立即更改iframe高度。例如,在提交后显示验证错误或“谢谢”消息。

我刚刚删除了嵌套的click()函数并将其放入我的iframe html中:

<script type="text/javascript">
    jQuery(document).ready(function () {
        var frame = $('#IDofiframeInMainWindow', window.parent.document);
        var height = jQuery("#IDofContainerInsideiFrame").height();
        frame.height(height + 15);
    });
</script>

为我工作,但不确定跨浏览器功能。

答案 11 :(得分:2)

使用上述方法都无法正常工作。

的javascript:

function resizer(id) {
        var doc = document.getElementById(id).contentWindow.document;
        var body_ = doc.body, html_ = doc.documentElement;

        var height = Math.max(body_.scrollHeight, body_.offsetHeight, html_.clientHeight, html_.scrollHeight, html_.offsetHeight);
        var width = Math.max(body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth);

        document.getElementById(id).style.height = height;
        document.getElementById(id).style.width = width;

    }

HTML:

<div style="background-color:#b6ff00;min-height:768px;line-height:inherit;height:inherit;margin:0px;padding:0px;overflow:visible" id="mainDiv"  >
         <input id="txtHeight"/>height     <input id="txtWidth"/>width     
        <iframe src="head.html" name="topFrame" scrolling="No" noresize="noresize" id="topFrame" title="topFrame" style="width:100%; height: 47px" frameborder="0"  ></iframe>
        <iframe src="left.aspx" name="leftFrame" scrolling="yes"   id="Iframe1" title="leftFrame" onload="resizer('Iframe1');" style="top:0px;left:0px;right:0px;bottom:0px;width: 30%; border:none;border-spacing:0px; justify-content:space-around;" ></iframe>
        <iframe src="index.aspx" name="mainFrame" id="Iframe2" title="mainFrame" scrolling="yes" marginheight="0" frameborder="0" style="width: 65%; height:100%; overflow:visible;overflow-x:visible;overflow-y:visible; "  onload="resizer('Iframe2');" ></iframe>
</div>

环境:IE 10,Windows 7 x64

答案 12 :(得分:2)

如果您可以控制IFRAME内容和父窗口,那么您需要iFrame Resizer

此库可以自动调整相同和跨域iFrame的高度和宽度,以适应其包含的内容。它提供了一系列功能来解决使用iFrame的最常见问题,其中包括:

  • 将iFrame的高度和宽度调整为内容大小。
  • 使用多个嵌套的iFrame。
  • 跨域iFrame的域身份验证。
  • 提供一系列页面大小计算方法,以支持复杂的CSS布局。
  • 检测可能导致页面使用MutationObserver调整大小的DOM更改。
  • 检测可能导致页面调整大小的事件(窗口调整大小,CSS动画和转换,方向更改和鼠标事件)。
  • 通过postMessage在iFrame和主页之间简化消息传递。
  • 修复了iFrame中的页面链接,并支持iFrame和父页面之间的链接。
  • 提供自定义大小调整和滚动方法。
  • 将父级位置和视口大小公开给iFrame。
  • 与ViewerJS一起使用以支持PDF和ODF文档。
  • 对IE8的支持。

答案 13 :(得分:1)

我发现这个缩放器可以更好地工作:

function resizer(id)
{

    var doc = document.getElementById(id).contentWindow.document;
    var body_ = doc.body;
    var html_ = doc.documentElement;

    var height = Math.max( body_.scrollHeight, body_.offsetHeight, html_.clientHeight,     html_.scrollHeight, html_.offsetHeight );
    var width  = Math.max( body_.scrollWidth, body_.offsetWidth, html_.clientWidth, html_.scrollWidth, html_.offsetWidth );

    document.getElementById(id).height = height;
    document.getElementById(id).width = width;

}

请注意,样式对象已被删除。

答案 14 :(得分:1)

如果有人来到这里: 我从iframe中删除div时遇到了问题 - iframe没有缩短。

有一个Jquery插件可以完成这项工作:

http://www.jqueryscript.net/layout/jQuery-Plugin-For-Auto-Resizing-iFrame-iFrame-Resizer.html

答案 15 :(得分:1)

经过一些实验后,我想出了另一个解决方案。我最初尝试将此问题标记为“最佳答案”的代码,但它无效。我的猜测是因为我当时的程序中的iframe是动态生成的。这是我使用的代码(它对我有用):

正在加载的iframe中的Javascript:

window.onload = function()
    {
        parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
        parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
    };
  

有必要在高度上添加4个或更多像素以移除滚动条(一些奇怪的错误/ iframe的效果)。宽度甚至更奇怪,您可以安全地将18px添加到身体的宽度。还要确保您已应用iframe主体的CSS(下方)。

html, body {
   margin:0;
   padding:0;
   display:table;
}

iframe {
   border:0;
   padding:0;
   margin:0;
}

以下是iframe的html:

<iframe id="fileUploadIframe" src="php/upload/singleUpload.html"></iframe>

以下是我的iframe中的所有代码:

<!DOCTYPE HTML>
<html>
<head>
    <meta charset="utf-8">
    <title>File Upload</title>
    <style type="text/css">
    html, body {
        margin:0;
        padding:0;
        display:table;
    }
    </style>
    <script type="text/javascript">
    window.onload = function()
    {
        parent.document.getElementById('fileUploadIframe').style.height = document.body.clientHeight+5+'px';
        parent.document.getElementById('fileUploadIframe').style.width = document.body.clientWidth+18+'px';
    };
    </script>
</head>
<body>
    This is a test.<br>
    testing
</body>
</html>

我已经在chrome中进行了测试,并在firefox中进行了一些测试(在windows xp中)。我还有更多的测试要做,所以请告诉我这对你有什么用。

答案 16 :(得分:1)

在jQuery中,这对我来说是最好的选择,真的对我有帮助!我等着你的帮助!

IFRAME

<iframe src="" frameborder="0" id="iframe" width="100%"></iframe>

的jQuery

<script>            
        var valueSize = $( "#iframe" ).offset();
        var totalsize = (valueSize.top * 2) + valueSize.left;

        $( "#iframe" ).height(totalsize);            

</script>

答案 17 :(得分:0)

如果您可以使用固定的长宽比,并且希望使用响应型iframe ,则此代码对您很有用。这只是CSS规则。

(pop)

iframe必须将div作为容器。

.iframe-container {
  overflow: hidden;
  /* Calculated from the aspect ration of the content (in case of 16:9 it is 9/16= 
  0.5625) */
  padding-top: 56.25%;
  position: relative;
}
.iframe-container iframe {
  border: 0;
  height: 100%;
  left: 0;
  position: absolute;
  top: 0;
  width: 100%;
}

源代码基于siteBen Marshall有一个很好的解释。

答案 18 :(得分:0)

很明显,有很多方案,但是,我对文档和iframe具有相同的域,因此能够将其附加到iframe内容的末尾:

var parentContainer = parent.document.querySelector("iframe[src*=\"" + window.location.pathname + "\"]");
parentContainer.style.height = document.body.scrollHeight + 50 + 'px';

这将“查找”父容器,然后通过添加50像素的软键来设置长度,以删除滚动条。

没有什么可以“观察”文档高度的变化,这对于我的用例来说并不需要。在我的回答中,我确实提供了一种引用父容器的方法,而无需使用嵌入到父/ iframe内容中的ID。

答案 19 :(得分:0)

上下文

我必须在网络扩展的背景下自己做。此网络扩展程序在每个页面中注入了一部分用户界面,并且该用户界面位于iframe中。 iframe内的内容是动态的,因此我不得不重新调整iframe本身的宽度和高度。

我使用 React ,但是这个概念适用于每个图书馆。

我的解决方案(假设您同时控制了页面和iframe)

iframe内,我更改了body的样式以具有很大的尺寸。这将允许使用所有必要的空间来布局内部的元素。使widthheight达到100%对我来说不起作用(我猜是因为iframe具有默认的width = 300pxheight = 150px

/* something like this */
body {
  width: 99999px;
  height: 99999px;
}

然后,我将所有iframe用户界面注入div并为其提供了一些样式

#ui-root {
  display: 'inline-block';     
}

在此#ui-root中渲染我的应用程序后(在 React 中,我在componentDidMount中完成此操作),我计算了该div的尺寸,并使用将该尺寸同步到父页面window.postMessage

let elRect = el.getBoundingClientRect()
window.parent.postMessage({
  type: 'resize-iframe',
  payload: {
    width: elRect.width,
    height: elRect.height
  }
}, '*')

在父框架中,我这样做:

window.addEventListener('message', (ev) => {
  if(ev.data.type && ev.data.type === 'resize-iframe') {
    iframe.style.width = ev.data.payload.width + 'px'
    iframe.style.height = ev.data.payload.height + 'px'
  }
}, false)

答案 20 :(得分:0)

这是我在加载时或事情发生变化时的方式。

parent.jQuery("#frame").height(document.body.scrollHeight+50);

答案 21 :(得分:0)

如果内容只是一个非常简单的html,最简单的方法是使用javascript删除iframe

HTML:

<div class="iframe">
    <iframe src="./mypage.html" frameborder="0" onload="removeIframe(this);"></iframe>
</div>

的javascript:

function removeIframe(obj)(
    var iframeDocument = obj.contentDocument || obj.contentWindow.document;
    var mycontent = iframeDocument.getElementsByTagName("body")[0].innerHTML;
    obj.remove();
    document.getElementsByClassName("iframe")[0].innerHTML = mycontent;
}

答案 22 :(得分:0)

对于angularjs指令属性:

G.directive ( 'previewIframe', function () {
return {
    restrict : 'A',
    replace : true,
    scope : true,
    link : function ( scope, elem, attrs ) {
        elem.on ( 'load', function ( e ) {
            var currentH = this.contentWindow.document.body.scrollHeight;
            this.style.height = eval( currentH ) + ( (25 / 100)* eval( currentH ) ) + 'px';
        } );
    }
};
} );

注意百分比,我插入它以便你可以计算通常为iframe,文本,广告等进行的缩放,如果没有实现缩放,只需输入0

答案 23 :(得分:0)

function resizeIFrameToFitContent(frame) {
if (frame == null) {
    return true;
}

var docEl = null;
var isFirefox = navigator.userAgent.search("Firefox") >= 0;

if (isFirefox && frame.contentDocument != null) {
    docEl = frame.contentDocument.documentElement;
} else if (frame.contentWindow != null) {
    docEl = frame.contentWindow.document.body;
}

if (docEl == null) {
    return;
}

var maxWidth = docEl.scrollWidth;
var maxHeight = (isFirefox ? (docEl.offsetHeight + 15) : (docEl.scrollHeight + 45));

frame.width = maxWidth;
frame.height = maxHeight;
frame.style.width = frame.width + "px";
frame.style.height = frame.height + "px";
if (maxHeight > 20) {
    frame.height = maxHeight;
    frame.style.height = frame.height + "px";
} else {
    frame.style.height = "100%";
}

if (maxWidth > 0) {
    frame.width = maxWidth;
    frame.style.width = frame.width + "px";
} else {
    frame.style.width = "100%";
}
}

ifram样式:

.myIFrameStyle {
   float: left;
   clear: both;
   width: 100%;
   height: 200px;
   padding: 5px;
   margin: 0px;
   border: 1px solid gray;
   overflow: hidden;
}

iframe代码:

<iframe id="myIframe" src="" class="myIFrameStyle"> </iframe>

脚本标签:

<script type="text/javascript">
   $(document).ready(function () {
      $('myIFrame').load(function () {
         resizeIFrameToFitContent(this);
      });
    });
</script>

答案 24 :(得分:0)

我就是这样做的(在FF / Chrome中测试):

<script type="text/javascript" src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
function autoResize(iframe) {
    $(iframe).height($(iframe).contents().find('html').height());
}
</script>

<iframe src="page.html" width="100%" height="100" marginheight="0" frameborder="0" onload="autoResize(this);"></iframe>

答案 25 :(得分:0)

要放入标题的Javascript:

private void setupNavigationDrawerContent(NavigationView navigationView) {
        navigationView.setNavigationItemSelectedListener(
                new NavigationView.OnNavigationItemSelectedListener() {
                    @Override
                    public boolean onNavigationItemSelected(MenuItem menuItem) {
                        switch (menuItem.getItemId()) {
                            case R.id.item_navigation_drawer_home:
                                menuItem.setChecked(true);
                                customizeToolBar(0);
                                setFragment(0);
                                drawerLayout.closeDrawer(GravityCompat.START);
                                return true;
                            case R.id.item_navigation_drawer_cart:
                                menuItem.setChecked(true);
                                customizeToolBar(1);
                                setFragment(1);
                                drawerLayout.closeDrawer(GravityCompat.START);
                                return true;
                                ...

以下是iframe html代码:

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

Css样式表

&GT;

<iframe class="spec_iframe" seamless="seamless" frameborder="0" scrolling="no" id="iframe" onload="javascript:resizeIframe(this);" src="somepage.php" style="height: 1726px;"></iframe>

答案 26 :(得分:0)

我知道这篇文章很老,但我相信这是另一种方法。我刚刚在我的代码上实现了。在页面加载和页面调整大小时都可以正常工作:

var videoHeight;
var videoWidth;
var iframeHeight;
var iframeWidth;

function resizeIframe(){
    videoHeight = $('.video-container').height();//iframe parent div's height
    videoWidth = $('.video-container').width();//iframe parent div's width

    iframeHeight = $('.youtubeFrames').height(videoHeight);//iframe's height
    iframeWidth = $('.youtubeFrames').width(videoWidth);//iframe's width
}
resizeIframe();


$(window).on('resize', function(){
    resizeIframe();
});

答案 27 :(得分:0)

有可能制作一个像鬼一样的IFrame,就像它不存在一样。

请参阅http://codecopy.wordpress.com/2013/02/22/ghost-iframe-crossdomain-iframe-resize/

基本上您使用的是事件系统parent.postMessage(..) https://developer.mozilla.org/en-US/docs/DOM/window.postMessage

适用于所有现代浏览器!

答案 28 :(得分:-1)

简单:

var iframe = $("#myframe");
$(iframe.get(0).contentWindow).on("resize", function(){
    iframe.width(iframe.get(0).contentWindow.document.body.scrollWidth);
    iframe.height(iframe.get(0).contentWindow.document.body.scrollHeight);
});

答案 29 :(得分:-1)

这仅使用内联CSS:

<iframe src="http://example.com" style="resize: both;"               
        onload="this.style.height=this.contentDocument.body.scrollHeight +'px'; this.style.width=this.contentDocument.body.scrollWidth +'px';"
        onresize="this.style.height=this.contentDocument.body.scrollHeight +'px'; this.style.width=this.contentDocument.body.scrollWidth +'px';">
</iframe>

答案 30 :(得分:-3)

<iframe src="..." style="border:none; width:100%; height: 100vh;"></iframe>
相关问题