Home > Web Front-end > JS Tutorial > body text

使用jQuery不判断浏览器高度解决iframe自适应高度问题_jquery

WBOY
Release: 2016-05-16 16:26:25
Original
1161 people have browsed it

这里介绍两个超级简单的方法,不用写什么判断浏览器高度、宽度啥的。

下面的两种方法自选其一就行了。一个是放在和iframe同页面的,一个是放在test.html页面的。

注意别放错了地方。
iframe的代码中,注意要写ID,没有ID查找不到

复制代码 代码如下:


方法一:

复制代码 代码如下:

//注意:下面的代码是放在和iframe同一个页面调用
$("#main").load(function(){
var mainheight = $(this).contents().find("body").height()+30;
$(this).height(mainheight);
});

方法二:

复制代码 代码如下:

//注意:下面的代码是放在test.html调用
$(window.parent.document).find("#main").load(function(){
var main = $(window.parent.document).find("#main");
var thisheight = $(document).height()+30;
main.height(thisheight);
});

在做项目的过程中需要使用iframe,但是iframe默认有一个高度,超过该默认高度的会内容会被隐藏起来,而小于该默认高度的内容呢又会把默认高度当成内容的高度,在经过寻找答案的过程中,找到了怎样去控制iframe高度自适应

iframe自适应高度本身是很简单的方法,就是在页面加载完成后,重新计算一下高度即可。

代码如下:

复制代码 代码如下:

//公共方法:设置iframe的高度以保证全部显示数据
//function SetPageHeight() {
//    var iframe = getUrlParam('ifname');
//    var myiframe = window.parent.document.getElementById(iframe);
//     iframeLoaded(myiframe);
//}
var iframeLoaded = function (iframe) {
    if (iframe.src.length > 0) {
        if (!iframe.readyState || iframe.readyState == "complete") {
            var bHeight =
            iframe.contentWindow.document.body.scrollHeight;
            var dHeight =
            iframe.contentWindow.document.documentElement.scrollHeight;
            var height = Math.max(bHeight, dHeight);
            iframe.height = height;
        }
    }
}
//分页时重新设置 iframe 高度 ; 修改后:iframe.name = iframe.id
var reSetIframeHeight = function()
{
    try {
        var oIframe = parent.document.getElementById(window.name);
        oIframe.height = 100;
        iframeLoaded(oIframe);
    }
    catch (err)
    {
        try {
         parent.document.getElementById(window.name).height = 1000;
          } catch (err2) { }
    }
}

调用reSetIframeHeight();方法即可。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!