[英]How to detect device orientation with JavaScript?
我已經看到了很多方法來檢測設備的屏幕方向,包括使用檢查來測試innerWidth和innerHeight,就像這樣。
function getOrientation(){
var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Primary";
return orientation;
}
但是,如果我想檢查屏幕方向的變化以及事件監聽器怎么辦? 我試過這段代碼,但它對我不起作用。
function doOnOrientationChange()
{
switch(window.orientation)
{
case -90:
case 90:
alert('landscape');
break;
default:
alert('portrait');
break;
}
}
window.addEventListener('orientationchange', doOnOrientationChange);
// Initial execution if needed
doOnOrientationChange();
它不會檢測設備方向,並且監聽器不會為我注冊(我正在使用Chrome的設備模擬器)。
有兩種方法可以做到這一點:
首先,根據Screen API文檔,使用> = Chrome 38,Firefox和IE 11,屏幕對象不僅可以查看方向,還可以在每次設備方向更改時注冊偵聽器。
screen.orientation.type
將明確告訴您方向是什么,對於偵聽器,您可以使用以下簡單的內容:
screen.orientation.onchange = function (){
// logs 'portrait' or 'landscape'
console.log(screen.orientation.type.match(/\w+/)[0]);
};
其次,為了與Safari等與Screen不兼容的其他瀏覽器兼容, 本文顯示您可以繼續在窗口大小調整時使用innerWidth和innerHeight。
function getOrientation(){
var orientation = window.innerWidth > window.innerHeight ? "Landscape" : "Portrait";
return orientation;
}
window.onresize = function(){ getOrientation(); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.