Не удается получить доступ к высоте div в Iframe - PullRequest
1 голос
/ 15 апреля 2020

вот моя проблема: размер моего 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 !");

I Я не видел, чтобы кто-нибудь говорил об этой проблеме, поэтому, если у кого-то есть идеи, я возьму это!

Ответы [ 2 ]

1 голос
/ 15 апреля 2020

Пожалуйста, поместите этот скрипт на родительскую страницу -

<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>
1 голос
/ 15 апреля 2020

Я думаю, вам нужно дождаться полной загрузки 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);
};
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...