document.documentElement.clientHeight || document.body.clientHeight 获取视口高度,兼容IE通过API获取IE浏览器窗口高度的详细实现
核心原理说明
IE浏览器(Internet Explorer)与其他现代浏览器在DOM模型实现上存在差异,获取视口高度主要依赖document.documentElement或document.body对象的clientHeight属性,需注意:

- IE8+支持
document.documentElement.clientHeight - IE7及以下需使用
document.body.clientHeight - 兼容模式下可能出现异常值
实现步骤
浏览器检测
// 检测IE版本函数
function detectIEVersion() {
const ua = window.navigator.userAgent;
if (/MSIE/.test(ua)) {
return parseInt(ua.split('MSIE')[1]);
} else if (/Trident/.test(ua)) { // IE11+
const rv = ua.split('rv:')[1].split('.')[0];
return parseInt(rv);
}
return false; // 非IE浏览器
}
高度获取函数
function getIEViewportHeight() {
const ieVersion = detectIEVersion();
if (!ieVersion) return null; // 非IE浏览器
// 根据版本选择适配方式
if (ieVersion >= 8) {
return document.documentElement.clientHeight;
} else if (ieVersion > 0) {
return document.body.clientHeight;
}
return null;
}
标准模式强制
<!-在HTML头部添加 --> <meta http-equiv="X-UA-Compatible" content="IE=edge">
浏览器兼容性对照表
| 属性 | IE6/7 | IE8+ | IE11+ | Chrome | Firefox | Safari |
|---|---|---|---|---|---|---|
document.body.clientHeight |
||||||
document.documentElement.clientHeight |
||||||
window.innerHeight |
完整代码示例
// 完整实现方案
function getViewportHeight() {
const ieVersion = detectIEVersion();
if (ieVersion) {
// IE专属处理
if (ieVersion >= 8) {
return document.documentElement.clientHeight;
} else {
return document.body.clientHeight;
}
} else {
// 现代浏览器方案
return window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
}
}
// 使用示例
console.log("视口高度:" + getViewportHeight() + "px");
相关问题与解答
Q1:为什么在IE中获取的高度包含地址栏/工具栏?
A:IE的clientHeight属性会包含窗口框架(如地址栏、工具栏),若需获取内容可视区域高度,需使用:
document.documentElement.clientHeight document.documentElement.clientTop;
Q2:如何排除滚动条对高度计算的影响?
A:当存在垂直滚动条时,可通过以下方式修正:

const height = document.documentElement.clientHeight; const hasScrollbar = document.documentElement.scrollHeight > height; const finalHeight = hasScrollbar ? height (window.innerWidth document.documentElement.clientWidth) : height;
到此,以上就是小编对于“api 得到ie高度”的问题就介绍到这了,希望介绍的几点解答对大家有用,有任何问题和不懂的,欢迎各位朋友在评论区讨论,给我留言。
【版权声明】:本站所有内容均来自网络,若无意侵犯到您的权利,请及时与我们联系将尽快删除相关内容!