2015-10-07 17 views
0

已經嘗試了包括jQuery移動解決方案(與其他jQuery發生衝突)上發現的不同選項的負載,我發現下面的代碼將檢測屏幕旋轉,我可以使用它來添加類。增強屏幕方向的javascript代碼

$(window).bind("resize", function(){ 
screenOrientation = ($(window).height() > $(window).width())? 90 : 0; 
$('.centerBoxContentsSubCat').addClass('mobile_landscape'); 
}); 

不過,我需要.removeClass時旋轉的其他方式。

我試着重複代碼,切換高度和寬度的位置,但這沒有奏效。 我試着將代碼更改爲

$(window).bind("resize", function(){ 
if(screenOrientation = ($(window).height() > $(window).width())? 90 : 0){ 
$('.centerBoxContentsSubCat').addClass('mobile_landscape'); 
}else{ 
$('.centerBoxContentsSubCat').removeClass('mobile_landscape'); 
} 
}); 

但是這也不起作用。

我實際上是使用@media查詢的CSS,但我需要強制在屏幕旋轉列計數的更改和所有其他嘗試都未能得到甚至關閉。

有關我要去哪裏的錯誤的任何建議?

回答

0

您需要使用orientationchange事件,而不是調整大小。

+0

我試圖從StackOverflow的和其他網站的這種例子不勝枚舉,無法得到它切換正確。 這就是我嘗試過的一個例子,也指出了一些方向變換的短處。 http://stackoverflow.com/questions/14019939/window-orientation-returns-different-values-in-ios-and-android 鑑於它是所有智能手機的基本特徵,事實上它是如此複雜得到可行的解決方案跨平臺是可笑的。 –

1

有兩種不同的方法可以處理這個問題。

首先是隨着事件方向的變化。

// Listen for orientation changes 
window.addEventListener("orientationchange", function() { 
    // Announce the new orientation number 
    alert(window.orientation); 
}, false); 

第二個是matchMedia。

// Find matches 
var mql = window.matchMedia("(orientation: portrait)"); 

// If there are matches, we're in portrait 
if(mql.matches) { 
    // Portrait orientation 
} else { 
    // Landscape orientation 
} 

// Add a media query change listener 
mql.addListener(function(m) { 
    if(m.matches) { 
     // Changed to portrait 
    } 
    else { 
     // Changed to landscape 
    } 
}); 

來源: http://davidwalsh.name/orientation-change

如果您需要支持舊的瀏覽器,我建議這個庫:

https://github.com/WickyNilliams/enquire.js/

+0

雖然你的答案是有效的,但它有一個缺點,這就是爲什麼我尋找別的東西。在哪裏顯示肖像的評論我添加了$('。centerBoxContentsSubCat')。removeClass('mobile_landscape'); ,並且它顯示了一個風景評論,我添加了$('。centerBoxContentsSubCat')。addClass('mobile_landscape'); 我發現的問題是,如果頁面已經加載設備已經在橫向視圖它沒有添加類。切換到縱向並返回將觸發addClass。 –

+0

嘗試使用媒體查詢。我在這裏做了一些工作:https://github.com/michaelBenin/node-startup/blob/develop/browser/js/mixins/device_manager.js –