如何在HTML的iframe中,获取被调用的页面的高度,并作为这个iframe的高度?

新手上路,请多包涵

HTML的内容:<iframe src="/123.htm" name="my111" id="my222" onload="gaodu()" width="100%" marginwidth="10px" frameborder="0" scrolling="no"></iframe>

请问如何获取“ /123.htm ”的高度,并将这个高度作为HTML中iframe标签的高度?
iframe调用的页面是同一个网站的不同网页,大概就是你们所谓的“同域”吧。请大神帮我不全代码,在index.html 中使用iframe,调用/123.html,将123.html的文本高度,设置为index.html 中iframe的高度。

跪求大神解答。。。急。。

阅读 2.4k
2 个回答

从SO搬运一个答案过来:

$('iframe').load(function() {
    this.style.height =
    this.contentWindow.document.body.offsetHeight + 'px';
});

别忘了先加载jQuery。


https://stackoverflow.com/que...

你试试,我这本地测试可以
<script>
        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;
                }
            }
        };

        window.onload = function() {
            setIframeHeight(document.getElementById('external-frame'));
        };
    </script>
    <iframe src="backtop.html" frameborder="0" scrolling="no" id="external-frame" onload="setIframeHeight(this)"></iframe>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题