现在需要在手机横竖屏的时候显示的网页的布局是不一样的。现行的解决方案是监听window的onresize事件,然后判断当前屏幕的宽高比。但是使用的过程中遇到两个问题:
1.如果你弹出输入法进行输入的时候,onresize事件也会触发的,但是这个时候如果处在竖屏下,获取出来的屏幕宽很有可能是比屏幕高要大的,这个时候得出的结果很明显是错误的。
2.在UC浏览器下获取的宽高不准确。
var utilResize = {
init : function() {
var ua = navigator.userAgent.toLowerCase();
this.isIos = (/(iphone|ipad|ipod)/i).test(ua);
this.canUseNativeFullApi = (/(qqbrowser|ucbrowser|micromessenger)/i).test(ua);
this.isModenBrowser = this.isIos | this.canUseNativeFullApi;//高级浏览器横竖屏监听重力感应事件
}
addOrientationListener : function() {
var self = this;
if (this.isModenBrowser) {console.log('use orientationchange');
window.addEventListener('orientationchange', function(){
self._orientationChangeHandler();
});
} else {console.log('use resize event');
$(window).resize(function() {
self._orientationChangeHandler();
});
}
},
_orientationChangeHandler : function() {
var self = this;
setTimeout(function() {
if ( window.orientation == 180 || window.orientation== 0 ) {
onsole.log('竖屏');////
} else if( window.orientation == 90 || window.orientation == -90 ) {//横屏
}
}, 300);
}
}
这是我最后的解决方案
可以使用css3 的媒体查询来实现
@media screen and (orientation:portrait) {
/* css[竖向定义样式] */
......
}
@media screen and (orientation:landscape) {
/* css[横向定义样式] */
......
}
监听 window 的 orientationchange 事件
javascript
window.addEventListener('orientationchange', function(event){ if ( window.orientation == 180 || window.orientation==0 ) { alert("竖屏"); } if( window.orientation == 90 || window.orientation == -90 ) { alert("横屏"); } });