mobile设备的横竖屏切换检测
orientationchange Event
我们可以选择在window对象上监听orientationchange
属性。比如:
// Listen for orientation changes
window.addEventListener("orientationchange", function() {
// Announce the new orientation number
alert(window.orientation);
alert(window.outerWidth);
alert(innerWidth);
}, false);
window.orientation的取值:
- 0: portrait
- 90: landscape rotated to the left
- -90: landscape rotated to the right
- 180: portrait, ipad下才能取到
resize Event
设备旋转的时候,window的resize事件也是被触发的。判断的方法是:
这是一段JS代码,可以查询对应的css媒体查询语句是否匹配。
// Find matches
var mql = window.matchMedia("(orientation: portrait)");
// If there are matches, we're in portrait
if(mql.matches) {
// Portrait orientation
} else {
// Landscape orientation
}
// Add a media query change listener
mql.addListener(function(m) {
if(m.matches) {
// Changed to portrait
}
else {
// Changed to landscape
}
});
Media Query
使用css媒体查询:
/* portrait */
@media screen and (orientation:portrait) {
/* portrait-specific styles */
}
/* landscape */
@media screen and (orientation:landscape) {
/* landscape-specific styles */
}