由于各个版本的浏览器对取得clientWidth/scrollTop/scrollHeight等属性的方法各有不同,并且楼主也有点傻傻分不清,所以本篇文章不详细讲述原理,只是总结了一些兼容各浏览器的常见用法,如有错误之处,欢迎留言纠正。 如果想了解原理,可以查看这篇文章:JS中关于clientWidth offsetWidth scrollWidth 等的含义
以下是正文
1、pageWidth、pageHeight
/*
*兼容各浏览器
* 取得浏览器可见区域的大小
* 包括滚动条的宽(17px),但不包括浏览器的标签页、网址输入框、书签栏、这三部分的宽
* pageWidth==clientWidth+滚动条的宽(17px)[如果有垂直滚动条]
* pageWidth==clientHeight+滚动条的高(17px)[如果有水平滚动条]
*/
var pageWidth = window.innerWidth; //IE9+、Firefox、Safari、Opera、Chrome
var pageHeight = window.innerHeight;
if(typeof pageWidth!="number"||typeof pageHeight!="number"){ //IE6
if(document.compatMode=="CSS1Compat"){ //标准模式下
pageWidth = document.documentElement.clientWidth;
pageHeight = document.documentElement.clientHeight;
} else{ //混杂模式下
pageWidth = document.body.clientWidth;
pageHeight = document.body.clientHeight;
}
}
2、clientHeight、clientWidth
/*
*兼容各浏览器,
*取得页面视口(viewport)大小
*clientHeight:视口(viewport)高度,不包括滚动条、浏览器的标签页、网址输入框、书签栏、这三部分的宽
*clientWidth:视口(viewport)的宽度,不包括滚动条的宽
*/
var clientHeight = document.documentElement.clientHeight || document.body.clientHeight;
var clientWidth = document.documentElement.clientWidth || document.body.clientWidth;
- pageWidth、pageHeight和clientWidth、clientHeight的不同之处在于:pageWidth、pageHeight包括滚动条的宽(17px),而clientWidth、clientHeight不包括滚动条的宽。 也就说,如果页面没有垂直滚动条的话,pageWidth==clientHeight,如果页面没有水平滚动条的话,pageHeight==clientHeight
为了让大家更好理解:可以参考这张示意图
3、scrollTop、scrollLeft
/*
*兼容各浏览器
*scrollTop:页面利用滚动条滚动到下方时,隐藏在滚动条上方的页面的高度;
*scrollLeft:页面利用滚动条滚动到右侧时,隐藏在滚动条左侧的页面的宽度;
*/
var scrollTop = document.documentElement.scrollTop || window.pageYOffset || document.body.scrollTop;
var scrollLeft = document.documentElement.scrollLeft || window.pageXOffset || document.body.scrollLeft;
4、scrollWidth、scrollHeight
/*
*兼容各浏览
*scrollHeight:文档区的高度
*scrollHWidth:文档区的宽度
*/
var scrollHeight = Math.max(document.documentElement.scrollHeight, document.body.scrollHeight);
var scrollWidth = Math.max(document.documentElement.scrollWidth, document.body.scrollWidth);