无法访问 Iframe 中 div 的高度



这是我的问题:iFrame的大小必须根据其中div的大小而变化,当我尝试获取该div的大小时,我尝试的所有操作都返回0

var childiFrame = document.getElementById("myDiv");
console.log(childiFrame,"here is my iframe");
var innerDoc = childiFrame.contentWindow.document; 
console.log(innerDoc,"here is the innerDoc where i have to find my div");
mdDiv =innerDoc.getElementById("md");
console.log(mdDiv,"here is my div !");// and i can see the clientHeight =245
var divHeight = mdDiv.clientHeight; // or offsetHeight or scrollHeight
console.log(divHeight,"the div height always equals 0 !");

我还没有看到有人谈论这个问题,所以如果有人有任何想法,我会接受的!

请将此脚本放入父页面-

<script>	
window.addEventListener('message', function(e) {
	var data = e.data.split('-'),
		scroll_height = data[0],
		iframe_id = data[1];
	if(iframe_id == 'iframe1')
		document.getElementById('iframe-container-1').style.height = scroll_height + 'px'; } , false);
</script>

将此脚本放入iframe

<script>
setInterval(function () {
window.top.postMessage(document.body.scrollHeight + '-' + 'iframe1', "*");
}, 500);
</script>

我认为您需要等待iframe首先使用onload事件完全加载,然后尝试访问mdDiv属性,如:

var childiFrame = document.getElementById("myDiv");
console.log(childiFrame, "here is my iframe");
childiFrame.onload = function() {
console.log('my iframe is loaded');
var innerDoc = childiFrame.contentDocument ? childiFrame.contentDocument : childiFrame.contentWindow.document;
console.log(innerDoc, "here is the innerDoc where i have to find my div");
mdDiv = innerDoc.getElementById("md");
console.log(mdDiv, "here is my div !");
var divHeight = mdDiv.clientHeight; // or offsetHeight or scrollHeight
console.log(divHeight);
};

最新更新