[英]Detect Phone orientation on load
這是否可以在頁面加載時使用 Javascript 檢查。 我知道您可以檢測到方向的變化,但是是否可以立即檢查手機的 state 是什么?
謝謝
您可以檢查視口的寬度和高度,看看哪個更大:
var isLandscapeMode = window.innerWidth > window.innerHeight;
if (isLandscapeMode) {
// fit page to wide orientation here...
}
有關移動設備上視口大小的更深入討論,請參閱http://www.quirksmode.org/mobile/viewports2.html
(更新代碼)
你可以這樣做...
var currOrientation= '';
/************************
* Changes the (obj) element's class, to
* -vrt (vertical)
* -hrz (horizontal)
* depending on its width
*************************/
var orientation = function( obj ){
var w = getWidth(),
h = getHeight();
if( w <= h && currOrientation !== 'vrt' ){
obj.className = 'vrt';
currOrientation = 'vrt';
}
else if( currOrientation !== 'hrz' ) {
obj.className = 'hrz';
currOrientation = 'hrz';
}
}
/************************
* Binding a repeating timer
************************/
var orientationINIT = function() {
var content;
if( (content = document.getElementsByTagName('body')[0]) != undefined ){
orientation( content );
var Orient = setInterval( function() {
orientation( content );
}, 500 ); //each 500ms a call for orientation change
}
}
應在頁面加載或 DOM 完成時(或在頁面底部)調用orientationINIT
其中 getHeight() 和 getWidth() 應該是簡單的函數,它們以數字形式返回窗口的寬度/高度。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.