var clientHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0;
既可以兼容所有浏览器也可以兼容怪异模式
封装client
function client() {
return {
width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0,
height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0
};
}
直接调用
window.onresize = function () {
var clientWidth = client().width;
console.log(clientWidth);
};
例,体会响应式布局的原理
<script>
//当页面宽度 大于 960 像素的时候 页面为红色并显示computer
//当页面宽度 大于 640 小于 960 页面为绿色并显示tablet
//剩下的情况为黄色并显示mobile
window.onresize = function () {
responsive();
};
responsive();
function responsive() {
console.log("非常消耗性能的代码");
if (client().width > 960) {//是电脑
document.body.style.backgroundColor = "red";
document.body.innerHTML = "computer";
} else if (client().width > 640) {//是平板
document.body.style.backgroundColor = "green";
document.body.innerHTML = "tablet";
} else {//手机
document.body.style.backgroundColor = "yellow";
document.body.innerHTML = "mobile";
}
}
function client() {
return {
width: window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth || 0,
height: window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight || 0
};
}
</script>