Iframe的高度[动态]每2秒

Iframe height [dynamic] for every 2 second

本文关键字:2秒 动态 高度 Iframe      更新时间:2023-09-26

我的问题是,当我加载iframe它正确设置iframe的高度,也当数据(内容)加载在iframe它自动设置高度,但当页面加载在iframe和设置高度相对页面内容,然后如果我减少或删除内容从加载的页面它不会降低iframe的高度。g当页面加载第一次高度设置100px,并动态加载页面上的数据iframe高度设置为150px,当我减少数据时,它不设置iframe的高度,它仍然是150px)。这是我的代码:

function setIframeHeight(iframe) {
    if (iframe) {
        var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
        if (iframeWin.document.body) {
            iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
        }
        setInterval("setIframeHeight_id('" + iframe.id + "')", 2000);
    }
    return false;
}
function setIframeHeight_id(iframeid) {
    var iframe = document.getElementById(iframeid);
    if (iframe) {
        var iframeWin = iframe.contentWindow || iframe.contentDocument.parentWindow;
        if (iframeWin.document.body) {
            iframe.height = iframeWin.document.documentElement.scrollHeight || iframeWin.document.body.scrollHeight;
        }
    }
    return false;
}
function resizeIframe(nm) {
    setIframeHeight(document.getElementById(nm));
}
HTML

 <iframe id="IframeData" scrolling="no" frameborder="0" width="100%" onload="resizeIframe('IframeData')" allowtransparency="true"></iframe>

我强烈建议您使用jQuery而不是普通的JavaScript。它本身不会创造奇迹,但肯定会帮助您缩短代码。

当涉及到你的问题时,为什么不使用百分比大小而不是固定像素大小?假设您的iframe的高度设置为100%,而不是150px。通过这种方式,下次你调整父容器的大小时,iframe本身就会拉伸到父容器的高度。