判断横屏竖屏方式(三种)

本文主要介绍了通过HTML,CSS,JS三种判断横屏竖屏的方法。具有很好的参考价值,下面跟着小编一起来看下吧

在做移动端页面的时候经常会遇到需要判断横屏还是竖屏。下面将目前已知的通过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为倒过来的竖屏模式);


在ipad、iphone网页开发中,我们很可能需要判断是横屏或者竖屏。Android和IOS刚好相反

下面介绍如何用 jQuery 判断iPad、iPhone、Android是横屏还是竖屏的方法

function orient() {
if (window.orientation == 90 || window.orientation == -90) {
//ipad、iphone竖屏;Andriod横屏
$("body").attr("class", "landscape");
orientation = 'landscape';
return false;
}
else if (window.orientation == 0 || window.orientation == 180) {
//ipad、iphone横屏;Andriod竖屏
$("body").attr("class", "portrait");
orientation = 'portrait';
return false;
}
}
//页面加载时调用
$(function(){
orient();
});
//用户变化屏幕方向时调用
$(window).bind( 'orientationchange', function(e){
orient();
});

屏幕方向对应的window.orientation值:

ipad: 90 或 -90 横屏

ipad: 0 或180 竖屏

Andriod:0 或180 横屏

Andriod: 90 或 -90 竖屏

转载于: http://www.jb51.net/article/105453.htm          http://www.jb51.net/article/89664.htm

猜你喜欢

转载自blog.csdn.net/a460550542/article/details/79879033