重点:
查看浏览器视口尺寸(body可编辑区域) IE8及IE8以下不兼容: 浏览器视口X轴尺寸:window.innerWidth 浏览器视口Y轴尺寸:window.innerHeight 标准模式或者说严格模式下,任意浏览器都兼容: 浏览器视口X轴尺寸:document.documentElement.clientWidth 浏览器视口Y轴尺寸:document.documentElement.clientHeight 怪异模式或者说混杂模式下的浏览器: 浏览器视口X轴尺寸:document.body.clientWidth 浏览器视口Y轴尺寸:document.body.clientHeight 如何判断浏览器当前的模式: document.compatMode可判断模式类型: 值为”BackCompat” : 怪异模式 值为”CSS1Compat” : 标准模式
<!DOCTYPE html><!--现在是标准模式或者说严格模式,如果想变成怪异模式或者说混杂模式,只需要把<!DOCTYPE html>删掉就可以了-->
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title></title>
</head>
<body>
</body>
<script>
/*
DOM基本操作:
查看浏览器视口尺寸(body可编辑区域)
IE8及IE8以下不兼容:
浏览器视口X轴尺寸:window.innerWidth
浏览器视口Y轴尺寸:window.innerHeight
标准模式或者说严格模式下,任意浏览器都兼容:
浏览器视口X轴尺寸:document.documentElement.clientWidth
浏览器视口Y轴尺寸:document.documentElement.clientHeight
怪异模式或者说混杂模式下的浏览器:
浏览器视口X轴尺寸:document.body.clientWidth
浏览器视口Y轴尺寸:document.body.clientHeight
如何判断浏览器当前的模式:
document.compatMode可判断模式类型:
值为”BackCompat” : 怪异模式
值为”CSS1Compat” : 标准模式
*/
const width = window.innerWidth;//浏览器视口X轴尺寸
const height = window.innerHeight;//浏览器视口Y轴尺寸
console.log(`width:${width}`);
console.log(`height:${height}`);
const width2 = document.documentElement.clientWidth;//浏览器视口X轴尺寸
const height2 = document.documentElement.clientHeight;//浏览器视口Y轴尺寸
console.log(`width:${width2}`);
console.log(`height:${height2}`);
const width3 = document.body.clientWidth;//浏览器视口X轴尺寸
const height3 = document.body.clientHeight;//浏览器视口Y轴尺寸
console.log(`width:${width3}`);
console.log(`height:${height3}`);
/*
根据刚刚上面这些获取浏览器视口的尺寸的方法,封装一个getViewportOffset方法:
*/
function getViewportOffset() {
if (window.innerWidth) {
return {
w: window.innerWidth,
h: window.innerHeight
}
} else {
if (document.compatMode === 'CSS1Compat') {
return {
w: document.documentElement.clientWidth,
h: document.documentElement.clientHeight
}
} else {
return {
w: document.body.clientWidth,
h: document.body.clientHeight,
}
}
}
}
</script>
</html>