您可以使用以下 jQuery 插件来完成此操作:
http://benalman.com/projects/jquery-postmessage-plugin/
然后将以下代码添加到您包含在 iframe 文档和父窗口中的 javascript 文件中:
var iFrames = [];
var iFrameCounter = 0;
// Get the parent page URL as it was passed in, for browsers that don't support
// window.postMessage
var parent_url = decodeURIComponent(document.location.hash.replace(/^#/, ''));
// The first param is serialized using $.param (if not a string) and passed to the
// parent window. If window.postMessage exists, the param is passed using that,
// otherwise it is passed in the location hash (that's why parent_url is required).
// The second param is the targetOrigin.
function SetHeight() {
var id = Number(parent_url.replace(/.*#(\d+)(?:&|$)/, '$1'));
$.postMessage({ if_height: $(document).outerHeight(true), id: id }, parent_url, parent);
};
// Adds the iframe for the given url to the given container
function CreateFrame(container, url) {
$(function () {
// Pass the parent page URL into the Iframe in a meaningful way
var src = url + '#' + encodeURIComponent(document.location.href + "#" + iFrameCounter);
// Append the iFrame into the DOM.
var html = '<iframe id="iFrame' + iFrameCounter + '" src="' + src + '" width="100%" scrolling="no" frameborder="0">Your browser lacks support for iFrames!<\/iframe>';
iFrames[iFrameCounter] = { id: "iFrame" + iFrameCounter, container: container, if_height: 0 };
// Add iFrame to DOM
$(container).append($(html));
iFrameCounter++;
});
}
$(function () {
// Setup a callback to handle the dispatched MessageEvent event. In cases where
// window.postMessage is supported, the passed event will have .data, .origin and
// .source properties. Otherwise, this will only have the .data property.
$.receiveMessage(function (e) {
// Get frameId
var id = Number(e.data.replace(/.*id=([\d-]*).*/, '$1'));
var frame = iFrames[id];
// Get the height from the passsed data.
var h = Number(e.data.replace(/.*if_height=([\d-]*).*/, '$1'));
if (!isNaN(h) && h > 0 && h !== frame.if_height) {
// Height has changed, update the iframe.
$("#" + frame.id).css("height", (frame.if_height = h));
$("#" + frame.id).css("min-height", (frame.if_height = h));
$("#" + frame.id).css("max-height", (frame.if_height = h));
// Also update the parent element of the iframe.
$("#" + frame.id).parent().css("height", (frame.if_height = h));
$("#" + frame.id).parent().css("min-height", (frame.if_height = h));
$("#" + frame.id).parent().css("max-height", (frame.if_height = h));
}
});
});
然后使用以下代码在父窗口中创建 iframe:
<script type="text/javascript">
$(document).ready(function () {
CreateFrame("#someiFrameContainer", url);
});
</script>
<div id="someiFrameContainer"></div>
然后每次 iFrame 内文档的高度发生变化时,都会从 iFrame 页面调用此函数:
SetHeight();
这将导致 iframe 页面向其父窗口发送一条包含其新总高度的消息(支持跨域),这将捕获该消息并更新 iframe 的大小。这要求父窗口还包括上面的脚本文件,因为该文件注册了事件和函数以在使用CreateFrame();时自动处理这些消息@