在引用页(B)上创建一个隐藏的 iframe,引用与本页(A)同域的代理页面(C),并将B的高度作为 C.location的hash 值, C获取这个 hash 值。因为C与A同域,可以通信,因此将这个 hash 传给A来设置 iframe 的高度
(function () {
var getHeight = function () {
return Math.min(document.documentElement.scrollHeight, document.body.scrollHeight);
};
var preHeight = getHeight(),
agent_iframe;
var createIframe = function (height) {
agent_iframe = document.createElement("iframe");
agent_iframe.style.height = "0";
agent_iframe.style.width = "0";
agent_iframe.style.border = "none";
agent_iframe.src = "C页面地址#" + height;
document.body.appendChild(agent_iframe);
}
createIframe(preHeight);
var checkHeight = function () {
var currentHeight = getHeight();
if (currentHeight != preHeight) {
agent_iframe.src = "C页面地址#" + currentHeight;
preHeight = currentHeight;
}
setTimeout(checkHeight, 500);
}
setTimeout(checkHeight, 500);
})();
// C页面脚本
(function () {
var preHeight = parseInt(window.location.hash.substring(1), 10),
ifrmae = window.top.document.getElementById("A页面iframe的ID");
ifrmae.height = preHeight;
setInterval(function () {
var newHeight = parseInt(window.location.hash.substring(1), 10);
if (newHeight !== preHeight) {
ifrmae.height = newHeight;
preHeight = newHeight;
}
}, 500);
})();
(function(){
// 使用了arale DOM
frame = D.get("frame_content_parent");
function reSetIframe(){
var frameContent = frame.contentWindow.document,
bodyHeight = Math.max(frameContent.documentElement.scrollHeight,frameContent.body.scrollHeight);
if (bodyHeight != D.getStyle(frame, "height")){
D.setStyle(frame, "height", bodyHeight + "px");
}
}
if(frame){
D.setStyle(frame,"height","auto");
setInterval(reSetIframe,300);
}
})();
详细说明:http://www.zhouqicf.com/javascript/iframe-auto-height
实践出真知