绵阳动力网站建设

判断手机移动端访问网站横屏竖屏的三种方法

时间:2017-02-21

判断手机移动端访问网站横屏竖屏的三种方法

在做手机移动端网站开发的时候经常会遇到需要判断横屏还是竖屏。下面将目前已知的通过HTML,CSS,JS三种判断方法记录下来,方便以后翻阅。

1、通过在html中分别引用横屏和竖屏的样式:

<link rel="stylesheet" media="all and (orientation:portrait)" href="portrait.css" rel="external nofollow" >  //引用竖屏的CSS
<link rel="stylesheet" media="all and (orientation:landscape)" href="landscape.css" rel="external nofollow" >  //引用横屏的CSS

2、CSS中通过媒体查询的方法来判断:

@media (orientation: portrait ){
  //竖屏CSS 
}
@media ( orientation: landscape ){
  //横屏CSS 
}

3、js判断是否为横屏竖屏:

window.addEventListener("onorientationchange" in window ? orientationchange" : "resize", function() {
    if (window.orientation === 180 || window.orientation === 0) { 
      alert('竖屏状态!');
    } 
    if (window.orientation === 90 || window.orientation === -90 ){ 
      alert('横屏状态!');
    } 
  }, false);

只要用户改变了设备的查看模式,就会触发onorientationchange事件。

orientation有4个值:0,90,-90,180

值为0和180的时候为竖屏(180为倒过来的竖屏);

90和-90时为横屏(-90为倒过来的竖屏模式)。

Copyright © 绵阳动力网站建设 www.kf51.cn All Rights Reserved 蜀ICP备08100083号

客服微信
客服微信
0816-6339181
客服微信
my_dongli