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

2025-05-29 0 33

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

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

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

复制代码 代码如下:


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

方法一:

复制代码 代码如下:


//注意:下面的代码是放在和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();方法即可。

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 使用jQuery不判断浏览器高度解决iframe自适应高度问题 https://www.kuaiidc.com/110955.html

相关文章

发表评论
暂无评论