繁体   English   中英

无法访问 Iframe 中 div 的高度

[英]Can't acces to the height of a div in an Iframe

这是我的问题:我的 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>

我认为您需要先使用onload事件等待 iframe 完全加载,然后尝试访问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);
};

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM