zl程序教程

您现在的位置是:首页 >  前端

当前栏目

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

jQuery浏览器 问题 使用 解决 判断 高度 适应
2023-06-13 09:15:36 时间

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

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

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

复制代码代码如下:


<iframesrc="test.html"id="main"width="700"height="300"frameborder="0"scrolling="auto"></iframe>

方法一:

复制代码代码如下:


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

方法二:

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

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

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

代码如下:

复制代码代码如下:
//公共方法:设置iframe的高度以保证全部显示数据
//functionSetPageHeight(){
//   variframe=getUrlParam("ifname");
//   varmyiframe=window.parent.document.getElementById(iframe);
//    iframeLoaded(myiframe);
//}
variframeLoaded=function(iframe){
   if(iframe.src.length>0){
       if(!iframe.readyState||iframe.readyState=="complete"){
           varbHeight=
           iframe.contentWindow.document.body.scrollHeight;
           vardHeight=
           iframe.contentWindow.document.documentElement.scrollHeight;
           varheight=Math.max(bHeight,dHeight);
           iframe.height=height;
       }
   }
}
//分页时重新设置iframe高度;修改后:iframe.name=iframe.id
varreSetIframeHeight=function()
{
   try{
       varoIframe=parent.document.getElementById(window.name);
       oIframe.height=100;
       iframeLoaded(oIframe);
   }
   catch(err)
   {
       try{
        parent.document.getElementById(window.name).height=1000;
         }catch(err2){}
   }
}

调用reSetIframeHeight();方法即可。