<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>js宽高的属性认识与应用</title>
</head>
<body>
<script type="text/javascript">
// IE9+ 以上浏览器支持
console.log('------------------------------');
console.log('浏览器窗口内容区宽度:', window.innerWidth);
console.log('浏览器窗口内容区高度:', window.innerHeight);
console.log('浏览器窗口宽度:', window.outerWidth);
console.log('浏览器窗口高度:', window.outerHeight);
console.log('------------------------------');
// 兼容性写法
window.innerWidth = window.innerWidth || document.documentElement.clientWidth;
window.innerHeight = window.innerHeight || document.documentElement.clientHeight;
console.log('--------------------------------');
console.log('屏幕像素宽:', screen.width);
console.log('屏幕像素高:', screen.height);
console.log('可用宽:', screen.availWidth);
console.log('可用高:', screen.availHeight);
// 兼容性写法 screenX(Y) Firefox的属性;
var screenLeft = window.screenLeft || screenX;
var screenTop = window.screenTop || screenY;
console.log('screenLeft:', window.screenLeft );
console.log('screenTop:', window.screenTop );
console.log('--------------------------------');
// JS中元素的可视宽高对应于CSS概念
document.body.clientWidth; // 相当于 padding-box的宽
document.body.clientHeight; // 相当于 padding-box的高
document.body.clientLeft; // 相当于取元素 border-left-width
document.body.clientTop; // 相当于取元素 border-top-width
document.body.offsetWidth; // 相当于 border-box的宽
document.body.offsetHeight; // 相当于 border-box的高
// 有兼容性
document.body.offsetLeft;
/* 1. IE8+及chrome中 offsetLeft = (offsetParent的margin-left) + (offsetParent的border-Left-width)
+ (offsetParent的padding-left) + (元素的margin-left);
2. Firefox中 offsetLeft = (offsetParent的margin-left) + (offsetParent的padding-left) + (元素的margin-left);
3. IE6,7中 offsetLeft = (offsetParent的padding-left) + (元素的margin-left);
综合以上问题,为了解决兼容性IE6,7和Firefox需注意让offsetParent 无margin, 无border
*/
document.body.offsetTop;
// JS滚动区域相关
document.body.scrollWidth;
/* 1. 元素宽度小于浏览器宽度 scrollWidth: 通常是浏览器窗口的内容区宽度;
* 2. 元素宽度大于浏览器宽度 scrollWidth: margin-box的宽度区域;
* */
document.body.scrollHeight;
/** 1. 元素高度小于浏览器高度 scrollHeight: 通常是浏览器窗口的内容区高度;
* 2. 元素宽度大于浏览器高度 scrollHeight: margin-box的高度区域;
* */
document.body.scrollLeft;
document.body.scrollTop;
/** 是该元素的显示(可见)的内容与该元素实际的内容的距离。**/
document.body.scrollLeftMax; // 表示一个元素横向滚动条可滚动的最大距离。
document.body.scrollTopMax; // 表示一个元素纵向滚动条可滚动的最大距离。
</script>
</body>
</html>
网友评论