先来官方的了解一下这三个属性:
- clientHeight:元素客户区的大小,指的是元素内容及其边框所占据的空间大小(视口大小)
- scrollHeight: 滚动大小,指的是包含滚动内容的元素大小(元素内容的总高度)
- offsetHeight: 偏移量,包含元素在屏幕上所用的所有可见空间(包括所有的内边距滚动条和边框大小,不包括外边距)
视口的大小,部分移动设备浏览器对innerWidth的兼容性不好,需要
document.documentElement.clientWidth或者document.body.clientWidth
来兼容(混杂模式下对document.documentElement.clientWidth不支持)。
使用方法 : getViewPort().width;
function getViewPort () {
if(document.compatMode == "BackCompat") { //浏览器嗅探,混杂模式
return {
width: document.body.clientWidth,
height: document.body.clientHeight
};
} else {
return {
width: document.documentElement.clientWidth,
height: document.documentElement.clientHeight
};
}
}
/获得文档的大小(区别与视口),与上面获取视口大小的方法如出一辙
function getDocumentPort () {
if(document.compatMode == "BackCompat") {
return {
width: document.body.scrollWidth,
height: document.body.scrollHeight
};
} else {
return {
width: Math.max(document.documentElement.scrollWidth,document.documentElement.clientWidth),
height: Math.max(document.documentElement.scrollHeight,document.documentElement.clientHeight)
}
}
}