監聽移動端屏幕的橫屏豎屏

移動端的設備提供了一個事件: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();});

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容