首页 > 解决方案 > 如何在 iframe 元素中获取动态添加的 body 元素

问题描述

在 iframe 元素中,我添加了一个 src 属性,当它加载时,将调用该函数,在这种情况下 document.body 指的是主体。

我已经尝试过使用$(document).ready(function() {})and document.body[1],但没有任何成功。

<iframe  id="inlineFrameExample" class="iframeDynamic" title="Inline Frame Example" width="300" name="myFrame" src="http://www.nu.nl" onload="resizeIframe(this)">
<html>
    <head></head>
    <body></body>
</html>

function resizeIframe() {

    let test = document.body;

    console.log(test);

    // What's the page height?
    var height = document.body.scrollHeight;

    // Going to 'pipe' the data to the parent through the helpframe..
    var pipe = document.getElementById('inlineFrameExample');

    // Cachebuster a precaution here to stop browser caching interfering
    newSource = pipe.src + '?height='+height+'&cacheb='+Math.random();
    pipe.style.height = height + 'px';
}

在我看来, document.body 不会引用正确的 body 元素。还要记住,这是一个动态添加的元素。我想选择它,然后在 iframe 中获取该 body 元素的特定高度。

标签: javascript

解决方案


推荐阅读