让页面中iframe 或者 div 高度自适应

本文介绍如何通过JavaScript代码获取页面高度并调整iframe或div的高度,以实现页面自适应布局,减少空白并兼容不同浏览器。同时,解决了一个页面在增加下拉列表搜索结果时高度异常增加的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

我们在项目中的开发标准分辨率是1024*768,但是在当今大屏幕显示器越来越普及的情况下,我们需要尽量让整个页面铺满,少留空白,同时兼容各种浏览器。在网上搜了一位高手朋友的代码,再此感谢那位仁兄。
要实现 iframe 或者 div 在 页面中的高度自适应,我们需要做两件事情:
1 取得 页面的高度 ,JS代码如下
/*
*获得页面的高度、宽度,兼容各种浏览器的方法
*@author fengf
*@createDate 2011-10-25
*/
function ___getPageSize() {
var xScroll, yScroll;
if (window.innerHeight && window.scrollMaxY) {
xScroll = window.innerWidth + window.scrollMaxX;
yScroll = window.innerHeight + window.scrollMaxY;
} else if (document.body.scrollHeight > document.body.offsetHeight){
// all but Explorer Mac
xScroll = document.body.scrollWidth;
yScroll = document.body.scrollHeight;
} else {
// Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
xScroll = document.body.offsetWidth;
yScroll = document.body.offsetHeight;
}
var windowWidth, windowHeight;
if (self.innerHeight) {
// all except Explorer
if(document.documentElement.clientWidth){
windowWidth = document.documentElement.clientWidth;
} else {
windowWidth = self.innerWidth;
}
windowHeight = self.innerHeight;
} else if (document.documentElement && document.documentElement.clientHeight) {
// Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
windowHeight = document.documentElement.clientHeight;
} else if (document.body) {
// other Explorers
windowWidth = document.body.clientWidth;
windowHeight = document.body.clientHeight;
}
// for small pages with total height less then height of the viewport
if(yScroll < windowHeight){
pageHeight = windowHeight;
} else {
pageHeight = yScroll;
}
// for small pages with total width less then width of the viewport
if(xScroll < windowWidth){
pageWidth = xScroll;
} else {
pageWidth = windowWidth;
}
arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
return arrayPageSize;
};

2 根据页面的高度,去设置 页面中 iframe 或者 div 的高度,这里有个div 或者iframe 的最小高度,iframe的高度一般等于页面的高度减去某一个固定高度,如下面300就是除去div后其他组件的固定高度
function resizeDivOrIFrame(){
document.getElementById("targetDiv").style.height = ___getPageSize[1]-300;
}

3 在页面中 启动一个线程,不断的调用
window.setInterval("resizeDivOrIFrame()", 200);

ps:遇到一个奇怪的问题: 有一个页面是一个带下拉列表搜索的,结果列表的高度一直在增加,不知其解。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值