一、關於cordova-plugin-screen-orientation插件:
Cordova插件以iOS,Android和windows-uwp的常用方式設置/鎖定屏幕方向。此插件基於Screen Orientation API,因此api與當前規範匹配。
該插件將以下內容添加到屏幕對象(window.screen
):
// lock the device orientation
.orientation.lock('portrait')
// unlock the orientation
.orientation.unlock()
// current orientation
.orientation
二、使用方法:
1.安裝插件:
cordova plugin add cordova-plugin-screen-orientation
Git 源代碼地址:https://github.com/apache/cordova-plugin-screen-orientation
2.指定Orientations 設置宣傳角度:
例如設置橫屏:
// set to either landscape
screen.orientation.lock('landscape');
// allow user rotate
screen.orientation.unlock();
// access current orientation
console.log('Orientation is ' + screen.orientation.type);
參數說明:
描述字符串 | 功能 |
---|---|
portrait-primary | 豎屏主方向 |
portrait-secondary | 豎屏次方向 |
landscape-primary | 橫屏主方向 |
landscape-secondary | 橫屏次方向 |
portrait | 豎屏方向(primary + secondary) |
landscape | 橫屏方向(primary + secondary) |
natural | 設備的自然方向 |
any | 鎖定四個方向,即鎖定當前屏幕方向 |
3.監聽屏幕宣傳事件:
screen.orientation.addEventListener('change', function(){
console.log(screen.orientation.type); // e.g. portrait
});
// OR
screen.orientation.onchange = function(){console.log(screen.orientation.type);
};
三、案例代碼:
測試版本:
document.querySelector('.chagerotate').onclick = function () {
//判斷橫豎類型,操作切換
//alert(screen.orientation.type);
console.info(screen.orientation);
if (screen.orientation.type.indexOf('landscape') > -1) {
screen.orientation.lock('portrait-primary').then(function (obj) {
console.log(obj);
}, function (obj) {
console.error(obj);
});
} else {
screen.orientation.lock('landscape-primary').then(function (obj) {
console.log(obj);
}, function (obj) {
console.error(obj);
});
}
}
更多: