I have a Help page, help.php that I am loading inside an iframe in main.php How can I get the height of this page once it has loaded in the iframe?

I am asking this because I can't style the height of to iframe to 100% or auto. That's why I think I need to use javascript.. I am using jQuery

CSS:

body {
    margin: 0;
    padding: 0;
}
.container {
    width: 900px;
    height: 100%;
    margin: 0 auto;
    background: silver;
}
.help-div {
    display: none;
    width: 850px;
    height: 100%;
    position: absolute;
    top: 100px;
    background: orange;
}
#help-frame {
    width: 100%;
    height: auto;
    margin:0;
    padding:0;
}

JS:

$(document).ready(function () {
    $("a.open-help").click(function () {
        $(".help-div").show();
        return false;
    })
})

HTML:

<div class='container'>
    <!-- -->
    <div class='help-div'>
        <p>This is a div with an iframe loading the help page</p>
        <iframe id="help-frame" src="../help.php" width="100%" height="100%" frameborder="1"></iframe>
    </div>  <a class="open-help" href="#">open Help in iFrame</a>

    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
</div>

推荐答案

好的,我终于找到了一个很好的解决方案:

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

因为有些浏览器(较旧的Safari和Opera)在CSS呈现之前报告onload已经完成,所以您需要设置一个微超时并清空,然后重新分配iframe的src.

$('iframe').load(function() {
    setTimeout(iResize, 50);
    // Safari and Opera need a kick-start.
    var iSource = document.getElementById('your-iframe-id').src;
    document.getElementById('your-iframe-id').src = '';
    document.getElementById('your-iframe-id').src = iSource;
});
function iResize() {
    document.getElementById('your-iframe-id').style.height = 
    document.getElementById('your-iframe-id').contentWindow.document.body.offsetHeight + 'px';
}

Jquery相关问答推荐

当父迪瓦是重复元素时,如何将一些子元素包裹在父迪瓦中

JQuery日期 Select 器未设置从jQuery中 Select 的月份起90天或3个月

使用jquery ui来回滑动切换

如何在jQuery中移动表格行?

提高 jQuery Select 器性能的好方法?

数据表警告(表 id = 'example'):无法重新初始化数据表

jQuery 库中使用的设计模式

为什么 jquery fadeIn() 不能与 .html() 一起使用?

JSON 服务在失败/错误时应该返回什么

为什么 Chrome 会忽略本地 jQuery cookie?

使用 JQuery / JavaScript 调用/单击 mailto 链接

如何在 Angular 4 中使用 jQuery 插件?

C# String.IsNullOrEmpty Javascript 等效项

用作 Google Chrome 书签

如何在 JavaScript 中的对象数组中查找值?

jquery更改div类的样式属性

页面加载后如何执行jquery代码?

使用 JQuery 的黄色淡入淡出效果

将多个参数传递给 jQuery ajax 调用

如何判断值是否为 JSON 对象?