我正在使用iframe来加载来自不同域的内容。我想根据内容的高度自动调整iframe的高度。
我使用了post message
,但它根据窗口的高度调整iframe的高度。
这是我的代码:
var length;
var myEventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var myEventListener = window[myEventMethod];
var myEventMessage = myEventMethod == "attachEvent" ? "onmessage" : "message";
myEventListener(myEventMessage, function (e) {
var y=document.getElementById(e.data.Id);
var x = e.data.Height;
y.height = x;
}, false);
document.addEventListener('DOMContentLoaded', function () {
var widgets = document.getElementsByClassName('Container');
length = widgets.length
for (var i = 0, len = length; i < len; i++) {
var url = widgets[i].getAttribute("data-url");
var element = document.createElement("iframe");
element.setAttribute("src", url);
element.setAttribute("id", "Iframe" + i);
widgets[i].appendChild(element);
var a = { "Id": "Iframe" + i, "Height": document.body.scrollHeight }
window.parent.postMessage(a, "*")
}
}, false);
我在这里使用document.body.scrollHeight
(当前的winodw的高度)而不是我想要iframe的身高。
答案 0 :(得分:0)
/* client.js */
function adjust_iframe_height(){
var iframeContainerH = $('#iframecontainer').height();
exactHeight = iframeContainerH +10;// Fetches the div content height
window.parent.postMessage(exactHeight,"*"); // allows this to post to any parent iframe regardless of domain
}
$(window).resize(function(){ // Use document ready if needed
setTimeout(function(){adjust_iframe_height()}, 2000); // Time Out Set for 5 sec to ensure that it is called after bootstrap auto alignment on resize
});
/* parent.js */
var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
var eventer = window[eventMethod];
var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";
eventer(messageEvent, function(e) {
document.getElementById('frame1').height = e.data + 'px';
}, false);