监听移动端屏幕的横屏竖屏

移动端的设备提供了一个事件:orientationChange事件

在设备旋转的时候,会触发这个事件,

// Listen for orientation changes

window.addEventListener("orientationchange",function() {

      // Announce the new orientation number

       alert(window.orientation);

},false);

orientation属性

它有三个值:0,90,-90

0为竖屏模式(portrait),-90意味着该设备横向旋转到右侧的横屏模式(landscape),而90表示该设备是横向旋转到左边的横屏模式(landscape)。



(function(){

varinit =function(){

varupdateOrientation =function(){

varorientation = window.orientation;

switch(orientation){

case90:

case-90:

orientation ='landscape';//这里是横屏

break;

default:

orientation ='portrait';//这里是竖屏

break;

}

//html根据不同的旋转状态,加上不同的class,横屏加上landscape,竖屏

//加上portrait

document.body.parentNode.setAttribute('class',orientation);

};

// 每次旋转,调用这个事件。

window.addEventListener('orientationchange',updateOrientation,false);

// 事件的初始化

updateOrientation();

};

window.addEventListener('DOMContentLoaded',init,false);

})();


因此可以根据不同的旋转状态加上class,所以我们的css就可以这样写了

/**竖屏 body显示红色**/

.portrait body div{

background: red;

}

/**横屏 body显示蓝色**/

.landscape body div{

background: blue;

}

另外一种写法是,借助 media queries

@media all and (orientation: portrait) {

body div {background: red;}

}

@media all and (orientation: landscape) {

body div {background: blue; }

}




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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容