Chen Yangjian's Blog

Carpe diem - Seize the day

JavaScript 获取 Iframe 内容高度

| Comments

页面中,有需要 iframe 嵌入的内容,因为是同源的内容,所以可以使用 JavaScript 操作起来,希望可以获取它需要的高度,修改 iframe 标签的 height,以去掉滚动条,让嵌入看起来更自然一点。

stackoverflow 上果然已经有了不少关于这个问题的问答,翻看一遍,总结解决办法如下:

iframe.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var frame = document.getElementById('#frame');

// 在 iframe onload 事件触发之后再执行:
frame.onload = function(){
    var win = frame.contentWindow,
        doc = win.document,
        html = doc.documentElement,
        body = doc.body;

    // [获取高度](http://stackoverflow.com/questions/1145850/get-height-of-entire-document-with-javascript)
    var height = Math.max( body.scrollHeight, body.offsetHeight,
                           html.clientHeight, html.scrollHeight, html.offsetHeight );

    frame.setAttribute('height', height);
};
frame.setAttribute('src', frame.getAttribute('data-src'));

这俩结合起来,就是我最终采取的方式啦。

Comments