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

发布于 2024-07-19 00:33:36 字数 175 浏览 11 评论 0 原文

我需要一个解决方案来自动调整iframe宽度高度以勉强适合其内容。 重点是,在加载 iframe 后可以更改宽度和高度。 我想我需要一个事件操作来处理 iframe 中包含的正文尺寸的变化。

I need a solution for auto-adjusting the width and height of an iframe to barely fit its content. The point is that the width and height can be changed after the iframe has been loaded. I guess I need an event action to deal with the change in dimensions of the body contained in the iframe.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(30

浅浅淡淡 2024-07-26 00:33:38

删除iframe

如果内容只是一个非常简单的html,最简单的方法是用javascript 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;
}

If the content is just a very simple html, the simplest way is to remove the iframe with javascript

HTML code:

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

Javascript code:

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;
}
忘年祭陌 2024-07-26 00:33:38

如果你正在寻找一个无 jQuery 跨源解决方案,你可能想看看我的想法:

<main id="container"></main>
<script>
  fetch('https://example.com').then(response => {
    return response.text();
  }).then(data => {
    const iframeContainer = window.document.getElementById('container');
    const iframe = document.createElement('iframe');
    iframe.frameBorder = 'none';
    iframe.width = '100%';
    iframe.addEventListener("load", function() {
      iframe.height = iframe.contentWindow.document.body.scrollHeight;
    })
    const finalHtml = data;
    const blob = new Blob([finalHtml], {type: 'text/html'});
    iframe.src = window.URL.createObjectURL(blob);
    iframeContainer.appendChild(iframe);
  })
</script>

If you are looking for a no jQuery cross-origin solution, you might want to look at my idea:

<main id="container"></main>
<script>
  fetch('https://example.com').then(response => {
    return response.text();
  }).then(data => {
    const iframeContainer = window.document.getElementById('container');
    const iframe = document.createElement('iframe');
    iframe.frameBorder = 'none';
    iframe.width = '100%';
    iframe.addEventListener("load", function() {
      iframe.height = iframe.contentWindow.document.body.scrollHeight;
    })
    const finalHtml = data;
    const blob = new Blob([finalHtml], {type: 'text/html'});
    iframe.src = window.URL.createObjectURL(blob);
    iframeContainer.appendChild(iframe);
  })
</script>
青衫负雪 2024-07-26 00:33:37

如果您不想使用 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;
}

Here is a cross-browser solution if you don't want to use 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;
}
无妨# 2024-07-26 00:33:37

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

索引.html

<style type="text/css">
html, body{
  width:100%;
  height:100%;
  overflow:hidden;
  margin:0px;   
}
</style>
<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="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></iframe>

After I have tried everything on the earth, this really works for me.

index.html

<style type="text/css">
html, body{
  width:100%;
  height:100%;
  overflow:hidden;
  margin:0px;   
}
</style>
<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="http://iframe.domain.com" width="100%" height="100%" marginheight="0" frameborder="0" border="0" scrolling="auto" onload="autoResize(this);"></iframe>
情场扛把子 2024-07-26 00:33:37

上下文

我必须自己在网络扩展的上下文中执行此操作。 此 Web 扩展将一些 UI 注入到每个页面中,并且此 UI 位于 iframe 内。 iframe 内的内容是动态的,因此我必须重新调整 iframe 本身的宽度和高度。

我使用 React 但这个概念适用于每个库。

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

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

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

然后我将所有 iframe UI 注入到 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)

Context

I had to do this myself in a context of a web-extension. This web-extension injects some piece of UI into each page, and this UI lives inside an iframe. The content inside the iframe is dynamic, so I had to readjust the width and height of the iframe itself.

I use React but the concept applies to every library.

My solution (this assumes that you control both the page and the iframe)

Inside the iframe I changed body styles to have really big dimensions. This will allow the elements inside to lay out using all the necessary space. Making width and height 100% didn't work for me (I guess because the iframe has a default width = 300px and height = 150px)

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

Then I injected all the iframe UI inside a div and gave it some styles

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

After rendering my app inside this #ui-root (in React I do this inside componentDidMount) I compute the dimensions of this div and sync them to the parent page using window.postMessage:

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

In the parent frame I do something like this:

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)
逆光下的微笑 2024-07-26 00:33:37

我使用此代码在所有 iframe(带有 autoHeight 类)加载到页面上时自动调整它们的高度。 经过测试,它可以在 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();
});

I am using this code to autoadjust height of all iframes (with class autoHeight) when they loads on page. Tested and it works in IE, FF, Chrome, Safari and 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();
});
酒儿 2024-07-26 00:33:37

这是一个可靠的证明解决方案

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 + "px";
document.getElementById(id).style.width = width + "px";

}

html

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

This is a solid proof solution

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 + "px";
document.getElementById(id).style.width = width + "px";

}

the html

<IFRAME SRC="some_page.php" id="iframe1"  onLoad="resizer('iframe1');"></iframe>
浅笑轻吟梦一曲 2024-07-26 00:33:37

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

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

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

If you can control both IFRAME content and parent window then you need the iFrame Resizer.

This library enables the automatic resizing of the height and width of both same and cross domain iFrames to fit their contained content. It provides a range of features to address the most common issues with using iFrames, these include:

  • Height and width resizing of the iFrame to content size.
  • Works with multiple and nested iFrames.
  • Domain authentication for cross domain iFrames.
  • Provides a range of page size calculation methods to support complex CSS layouts.
  • Detects changes to the DOM that can cause the page to resize using MutationObserver.
  • Detects events that can cause the page to resize (Window Resize, CSS Animation and Transition, Orientation Change and Mouse events).
  • Simplified messaging between iFrame and host page via postMessage.
  • Fixes in page links in iFrame and supports links between the iFrame and parent page.
  • Provides custom sizing and scrolling methods.
  • Exposes parent position and viewport size to the iFrame.
  • Works with ViewerJS to support PDF and ODF documents.
  • Fallback support down to IE8.
鹤仙姿 2024-07-26 00:33:37

如果您可以接受固定宽高比,并且想要一个响应式 iframe,那么此代码将对您有用。 这只是 CSS 规则。

.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%;
}

iframe 必须有一个 div 作为容器。

<div class="iframe-container">
   <iframe src="http://example.org"></iframe>
</div>

源代码基于此网站Ben Marshall 有一个很好的解释。

If you can live with a fixed aspect ratio and you would like a responsive iframe, this code will be useful to you. It's just CSS rules.

.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%;
}

The iframe must have a div as container.

<div class="iframe-container">
   <iframe src="http://example.org"></iframe>
</div>

The source code is based on this site and Ben Marshall has a good explanation.

执着的年纪 2024-07-26 00:33:37

我在这里阅读了很多答案,但几乎每个人都给出了某种跨源框架块。

错误示例:

未捕获的 DOMException:阻止了来源为“null”的框架
访问跨源框架。

相关线程中的答案也是如此:

Make iframe 自动根据内容调整高度而不使用滚动条?

我不想要使用第三方库,例如 iFrame Resizer 或类似的库。

@bboydflo 的答案很接近,但我缺少一个完整的示例。 https://stackoverflow.com/a/52204841/3850405

我正在使用 width="100%" 适用于 iframe,但也可以修改代码以使用宽度。

这就是我解决为 iframe 设置自定义高度的方法:

嵌入式 iframe

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description"
          content="Web site" />
    <title>Test with embedded iframe</title>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <iframe id="ifrm" src="https://localhost:44335/package/details?key=123" width="100%"></iframe>
    <script type="text/javascript">
        window.addEventListener('message', receiveMessage, false);

        function receiveMessage(evt) {
            console.log("Got message: " + JSON.stringify(evt.data) + " from origin: " + evt.origin);
            // Do we trust the sender of this message?
            if (evt.origin !== "https://localhost:44335") {
                return;
            }

            if (evt.data.type === "frame-resized") {
                document.getElementById("ifrm").style.height = evt.data.value + "px";
            }
        }
    </script>
</body>
</html>

iframe 源,来自 Create React App 的示例code> 但仅使用 HTMLJS

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description"
          content="Web site created using create-react-app" />
    <title>React App</title>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script type="text/javascript">
        //Don't run unless in an iframe
        if (self !== top) {
            var rootHeight;
            setInterval(function () {
                var rootElement = document.getElementById("root");
                if (rootElement) {
                    var currentRootHeight = rootElement.offsetHeight;
                    //Only send values if height has changed since last time
                    if (rootHeight !== currentRootHeight) {
                        //postMessage to set iframe height
                        window.parent.postMessage({ "type": "frame-resized", "value": currentRootHeight }, '*');
                        rootHeight = currentRootHeight;
                    }
                }
            }
                , 1000);
        }
    </script>
</body>
</html>

setInterval 的代码当然可以修改,但它对于动态内容非常有效。 setInterval 仅在内容嵌入到 iframe 中时激活,并且 postMessage 仅在高度发生变化时发送消息。

您可以在此处阅读有关 Window.postMessage() 的更多信息,但该描述非常适合我们想要实现的目标:

window.postMessage()方法可以安全地启用跨域
Window对象之间的通信; 例如,在页面和页面之间
它生成的弹出窗口,或者在页面和嵌入的 iframe 之间
在其中。

正常情况下,不同页面的脚本是允许互相访问的
当且仅当它们源自的页面共享相同的协议时,
端口号和主机(也称为“同源策略”)。
window.postMessage() 提供了一种安全的受控机制
规避此限制(如果使用得当)。

https://developer.mozilla.org/en-US/ docs/Web/API/Window/postMessage

如果你想要 iframe 的宽度和高度为 100%,我会这样做:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description"
          content="Web site" />
    <style>
        body {
            margin: 0; /* Reset default margin */
        }

        iframe {
            display: block; /* iframes are inline by default */
            background: #000;
            border: none; /* Reset default border */
            height: 100vh; /* Viewport-relative units */
            width: 100vw;
        }
    </style>
    <title>Test with embedded iframe</title>
</head>
<body>
    <iframe src="https://localhost:44335/package/details?key=123"></iframe>
</body>
</html>

来源:

https://stackoverflow.com/a/27853830/3850405

I have been reading a lot of the answers here but nearly everyone gave some sort of cross-origin frame block.

Example error:

Uncaught DOMException: Blocked a frame with origin "null" from
accessing a cross-origin frame.

The same for the answers in a related thread:

Make iframe automatically adjust height according to the contents without using scrollbar?

I do not want to use a third party library like iFrame Resizer or similar library either.

The answer from @bboydflo is close but I'm missing a complete example. https://stackoverflow.com/a/52204841/3850405

I'm using width="100%" for the iframe but the code can be modified to work with width as well.

This is how I solved setting a custom height for the iframe:

Embedded iframe:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description"
          content="Web site" />
    <title>Test with embedded iframe</title>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <iframe id="ifrm" src="https://localhost:44335/package/details?key=123" width="100%"></iframe>
    <script type="text/javascript">
        window.addEventListener('message', receiveMessage, false);

        function receiveMessage(evt) {
            console.log("Got message: " + JSON.stringify(evt.data) + " from origin: " + evt.origin);
            // Do we trust the sender of this message?
            if (evt.origin !== "https://localhost:44335") {
                return;
            }

            if (evt.data.type === "frame-resized") {
                document.getElementById("ifrm").style.height = evt.data.value + "px";
            }
        }
    </script>
</body>
</html>

iframe source, example from Create React App but only HTML and JS is used.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description"
          content="Web site created using create-react-app" />
    <title>React App</title>
</head>
<body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
    <script type="text/javascript">
        //Don't run unless in an iframe
        if (self !== top) {
            var rootHeight;
            setInterval(function () {
                var rootElement = document.getElementById("root");
                if (rootElement) {
                    var currentRootHeight = rootElement.offsetHeight;
                    //Only send values if height has changed since last time
                    if (rootHeight !== currentRootHeight) {
                        //postMessage to set iframe height
                        window.parent.postMessage({ "type": "frame-resized", "value": currentRootHeight }, '*');
                        rootHeight = currentRootHeight;
                    }
                }
            }
                , 1000);
        }
    </script>
</body>
</html>

The code with setInterval can of course be modified but it works really well with dynamic content. setInterval only activates if the content is embedded in a iframe and postMessage only sends a message when height has changed.

You can read more about Window.postMessage() here but the description fits very good in what we want to achieve:

The window.postMessage() method safely enables cross-origin
communication between Window objects; e.g., between a page and a
pop-up that it spawned, or between a page and an iframe embedded
within it.

Normally, scripts on different pages are allowed to access each other
if and only if the pages they originate from share the same protocol,
port number, and host (also known as the "same-origin policy").
window.postMessage() provides a controlled mechanism to securely
circumvent this restriction (if used properly).

https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

If you want 100% width and height for iframe I would do it like this:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8" />
    <meta name="description"
          content="Web site" />
    <style>
        body {
            margin: 0; /* Reset default margin */
        }

        iframe {
            display: block; /* iframes are inline by default */
            background: #000;
            border: none; /* Reset default border */
            height: 100vh; /* Viewport-relative units */
            width: 100vw;
        }
    </style>
    <title>Test with embedded iframe</title>
</head>
<body>
    <iframe src="https://localhost:44335/package/details?key=123"></iframe>
</body>
</html>

Source:

https://stackoverflow.com/a/27853830/3850405

你的他你的她 2024-07-26 00:33:37

我稍微修改了 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>

对我有用,但不确定跨浏览器功能。

I slightly modified Garnaph's great solution above. It seemed like his solution modified the iframe size based upon the size right before the event. For my situation (email submission via an iframe) I needed the iframe height to change right after submission. For example show validation errors or "thank you" message after submission.

I just eliminated the nested click() function and put it into my 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>

Worked for me, but not sure about cross browser functionality.

梦明 2024-07-26 00:33:37

使用以上方法都无法工作。

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

all can not work using above methods.

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>

Env: IE 10, Windows 7 x64

笔芯 2024-07-26 00:33:37

经过一番试验,我找到了另一种解决方案。 我最初尝试了标记为这个问题的“最佳答案”的代码,但它不起作用。 我的猜测是因为我当时程序中的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 的一些奇怪的错误/效果)。 宽度更奇怪,你可以安全地在 body 的宽度上添加 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 中)。 我还有更多测试要做,所以请告诉我这对你来说如何。

I figured out another solution after some experimenting. I originally tried the code marked as 'best answer' to this question and it didn't work. My guess is because my iframe in my program at the time was dynamically generated. Here is the code I used (it worked for me):

Javascript inside the iframe that is being loaded:

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';
    };

It is necessary to add 4 or more pixels to the height to remove scroll bars (some weird bug/effect of iframes). The width is even stranger, you are safe to add 18px to the width of the body. Also make sure that you have the css for the iframe body applied (below).

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

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

Here is the html for the iframe:

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

Here is all the code within my 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>

I have done testing in chrome and a little in firefox (in windows xp). I still have more testing to do, so please tell me how this works for you.

悟红尘 2024-07-26 00:33:37

可以制作一个“类似幽灵”的 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

这适用于所有现代浏览器!

It is possible to make a "ghost-like" IFrame that acts like it was not there.

See http://codecopy.wordpress.com/2013/02/22/ghost-iframe-crossdomain-iframe-resize/

Basically you use the event system parent.postMessage(..) described in
https://developer.mozilla.org/en-US/docs/DOM/window.postMessage

This works an all modern browsers!

苏璃陌 2024-07-26 00:33:37

这里有几种方法:

<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>

代码

<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% 的宽度和高度,这会强制滚动条位于页面之外,并且由于主体没有滚动条,人们可能不会期望 iframe 超出页面的边界。 这会隐藏全宽 iFrame 的滚动条!

来源:设置 iframe 自动高度

Here are several methods:

<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>

AND ANOTHER ALTERNATIVE

<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>

TO HIDE SCROLLING WITH 2 ALTERNATIVES AS SHOWN ABOVE

<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>

To hide the scroll-bars of the iFrame, the parent is made "overflow:hidden" to hide scrollbars and the iFrame is made to go upto 150% width and height which forces the scroll-bars outside the page and since the body doesn't have scroll-bars one may not expect the iframe to be exceeding the bounds of the page. This hides the scrollbars of the iFrame with full width!

source: set iframe auto height

深白境迁sunset 2024-07-26 00:33:37

如果有人到达这里:
当我从 iframe 中删除 div 时,我遇到了解决方案的问题 - iframe 并没有变短。

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

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

In case someone getting to here:
I had a problem with the solutions when I removed divs from the iframe - the iframe didnt got shorter.

There is an Jquery plugin that does the job:

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

ㄖ落Θ余辉 2024-07-26 00:33:37

我发现这个缩放器工作得更好:

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;

}

注意样式对象已被删除。

I found this resizer to work better:

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;

}

Note the style object is removed.

坏尐絯℡ 2024-07-26 00:33:37

在 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>

In jQuery, this is the best option to me, that really help me!! I wait that help you!

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>
一抹微笑 2024-07-26 00:33:37

显然有很多场景,但是,我的文档和 iframe 具有相同的域,并且我能够将其附加到我的 iframe 内容的末尾:

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

这“找到”父容器,然后设置添加模糊因子的长度50 像素以删除滚动条。

没有任何东西可以“观察”文档高度的变化,这对于我的用例来说是不需要的。 在我的回答中,我确实引入了一种引用父容器的方法,而不使用嵌入到父/iframe 内容中的 id。

Clearly there are lots of scenarios, however, I had same domain for document and iframe and I was able to tack this on to the end of my iframe content:

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

This 'finds' the parent container and then sets the length adding on a fudge factor of 50 pixels to remove the scroll bar.

There is nothing there to 'observe' the document height changing, this I did not need for my use case. In my answer I do bring a means of referencing the parent container without using ids baked into the parent/iframe content.

自由如风 2024-07-26 00:33:37
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%";
}
}

iframe 样式:

.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>
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 style:

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

iframe tag:

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

Script tag:

<script type="text/javascript">
   $(document).ready(function () {
      $('myIFrame').load(function () {
         resizeIFrameToFitContent(this);
      });
    });
</script>
救赎№ 2024-07-26 00:33:37

这就是我的做法(在 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>

This is how I would do it (tested in 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>
早茶月光 2024-07-26 00:33:37

我知道这篇文章很旧,但我相信这是另一种方法。 我刚刚在我的代码上实现了。 在页面加载和页面调整大小时都能完美运行:

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();
});

I know the post is old, but I believe this is yet another way to do it. I just implemented on my code. Works perfectly both on page load and on page resize:

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();
});
嗳卜坏 2024-07-26 00:33:37

Javascript 放置在标题中:

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

这里是 iframe html 代码:

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

Css 样式表

>

.spec_iframe {
        width: 100%;
        overflow: hidden;
    }

Javascript to be placed in header:

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

Here goes iframe html code:

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

Css stylesheet

>

.spec_iframe {
        width: 100%;
        overflow: hidden;
    }
油焖大侠 2024-07-26 00:33:37

对于 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

For angularjs directive attribute:

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';
        } );
    }
};
} );

Notice the percentage, i inserted it so that you can counter scaling usually done for iframe, text, ads etc, simply put 0 if no scaling is implementation

花之痕靓丽 2024-07-26 00:33:37

这就是我在加载或事情发生变化时的做法。

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

This is how I did it onload or when things change.

parent.jQuery("#frame").height(document.body.scrollHeight+50);
你爱我像她 2024-07-26 00:33:36
<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>
<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>
做个ˇ局外人 2024-07-26 00:33:36

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

<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>

one-liner solution for embeds:
starts with a min-size and increases to content size. no need for script tags.

<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>

浅蓝的眸勾画不出的柔情 2024-07-26 00:33:36

跨浏览器jQuery 插件

跨浏览器、跨域库,名为 iframe-resizer,使用 resizeObserver mutationObserver 来保持 iFrame 的大小适合内容,以及 postMessage 来在 iFrame 和主机页面之间进行通信。 有 React、Vue 和 jQuery 版本。

Cross-browser jQuery plug-in.

Cross-bowser, cross domain library called iframe-resizer that uses resizeObserver and mutationObserver to keep iFrame sized to the content and postMessage to communicate between iFrame and host page. Has versions for React, Vue and jQuery.

北座城市 2024-07-26 00:33:36

迄今为止给出的所有解决方案仅考虑一次调整大小。 您提到您希望能够在修改内容后调整 iFrame 的大小。 为此,您需要在 iFrame 内执行一个函数(一旦内容发生更改,您需要触发一个事件来表明内容已更改)。

我被这个问题困扰了一段时间,因为 iFrame 内部的代码似乎仅限于 iFrame 内部的 DOM(并且无法编辑 iFrame),而在 iFrame 外部执行的代码则被困在 iFrame 外部的 DOM 中(并且无法编辑) t 获取来自 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>

All solutions given thus far only account for a once off resize. You mention you want to be able to resize the iFrame after the contents are modified. In order to do this, you need to execute a function inside the iFrame (once the contents are changed, you need to fire an event to say that the contents have changed).

I was stuck with this for a while, as code inside the iFrame seemed limited to the DOM inside the iFrame (and couldn't edit the iFrame), and code executed outside the iFrame was stuck with the DOM outside the iFrame (and couldn't pick up an event coming from inside the iFrame).

The solution came from discovering (via assistance from a colleague) that jQuery can be told what DOM to use. In this case, the DOM of the parent window.

As such, code such as this does what you need (when run inside the 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>
我恋#小黄人 2024-07-26 00:33:36

如果 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>

If the iframe content is from the same domain this should work great. It does require jQuery though.

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

To have it resize dynamically you could do this:

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

Then on the page that the iframe loads add this:

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

$(window).on('resize', resize);
</script>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文