可能我们在写移动端项目的时候会有要求或者为了更好的体验会做横竖屏检测,以达到更好的用户体验。
// 判断横竖屏
var utils = {
debounce: function(func,delay){
var timer = null;
return function(){
var context = this,
args = arguments;
clearTimeout(timer);
timer = setTimeout(function(){
func.apply(context,args);
},delay);
}
}
}
var detectRes = document.getElementById('J_detectRes');
var detectData = document.getElementById('J_detectData');
function detectOrient() {
var storage = localStorage; // 不一定要使用localStorage,其他存储数据的手段都可以
var data = storage.getItem('J-recordOrientX');
var cw = document.documentElement.clientWidth;
var _Width = 0,
_Height = 0;
if(!data) {
sw = window.screen.width;
sh = window.screen.height;
// 2.在某些机型(如华为P9)下出现 srceen.width/height 值交换,所以进行大小值比较判断
_Width = sw < sh ? sw : sh;
_Height = sw >= sh ? sw : sh;
storage.setItem('J-recordOrientX',_Width + ',' + _Height);
}else {
var str = data.split(',');
_Width = str[0];
_Height = str[1];
}
if(cw == _Width) {
// 竖屏
return;
}
if(cw == _Height){
// 横屏
return;
}
}
// 3.函数去抖处理
window.onresize = utils.debounce(detectOrient,300);
detectOrient();
详细介绍请参考原作者文章 探讨判断横竖屏的最佳实现