在移动端,判断横竖屏的场景并不少见,不用形式关系到不同的样式处理,比较有名的前端UI框架Bootstrap,里面的很多代码都是针对不同大小尺寸宽度而设计的,所以在处理横竖屏的UI显示上做到了兼容处理,里面有几个比较多的尺寸就是768px, 992px,1200px。
CSS的媒体查询
<style type='text/css'><!--内嵌样式判断-->
@media screen and (orientation:landscape){
//横屏
}
@media screen and (orientation:portrait){
//竖屏
}
</style><!--外联样式判断-->
<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css"/>
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css"/>
JS判断是否横竖屏幕
window.matchMedia()
window.matchMedia()这个方法是对CSSOM的 CSS Media Queries,可以通过js来查询媒体。使用方式是通过传递字符串媒体参数orientation:portrait
或orientation:landscape
,然后会返回一个MediaQueryList对象。目前兼容所有的移动端。 具体的使用方法:
var mql = window.matchMedia("(orientation: portrait)");
function onMatchMeidaChange(mql){
if(mql.matches) {
console.log('portraint')
}else {
console.log('landscape')
}
}
mql.addListener(onMatchMeidaChange(mql));
MediaQueryList包含两个对象(media和matches),并且提供了onchange方法.
window.orientation
这个大家可能用的比较少,但是它有一个事件类型orientationchange
肯定很常用,如果是在前端开发过程中使用过rem同学肯定知道
var resizeEvent = "orientationchange" in window ? "orientationchange" : "resize";
通过判断偏离的角度值来判断是否横竖屏幕。
- 0:代表此时是默认屏幕方向
- 90:代表顺时针偏离默认屏幕方向90度
- -90:代表逆时针偏离屏幕方向90度
- 180:代表偏离默认屏幕方向180度
switch(window.orientation) {
case 0:
displayStr += "Portrait";
break;
case -90:
displayStr += "Landscape (right, screen turned clockwise)";
break;
case 90:
displayStr += "Landscape (left, screen turned counterclockwise)";
break;
case 180:
displayStr += "Portrait (upside-down portrait)";
break;
}
上面的可以参考文末的苹果手册文档,
**window.innerHeight/window.innerWidth **
通过判断高度是否大于宽度,一般情况下高度大于宽度是竖屏,反之是横屏。但是Nokia曾经有一款与之相反的设备,幸好现在被淘汰了。
function detectOrient(){
if(window.innerHeight >= window.innerWidth) {
// 竖屏
}else {
// 横屏
}
}
detectOrient();
window.addEventListener('resize',detectOrient);
参考资料: iOS Developer Library – Handling Orientation Events