mobile-webapp JS的屏幕锁定方向

时间:2014-11-20 23:06:36

标签: javascript jquery html css screen-lock

我尝试使用实验性屏幕方向API:
http://www.w3.org/TR/screen-orientation/

我可以通过此MDN推荐来实现这一点:
https://developer.mozilla.org/en-US/docs/Web/API/Screen.lockOrientation

现在是否已经存在javascript / jquery插件,没有css旋转技巧或js反转高度和宽度?

THX!

1 个答案:

答案 0 :(得分:1)

这是我提出的一个解决方案,虽然有点hacky。

<强> HTML

<div class="wrap">
    <header></header>
</div>

<强> CSS

html, body {
    margin:0;
    position:relative;
}
.wrap {
    background-color:black;
    width:300px;
    margin:0 auto;
    height:500px;
}
header {
    background-color:red;
    width:100%;
    height:80px;
}
.rotate {
    float:left;
    transform: rotate(-90deg);
}
.rotate:after { content:'';clear:both;width:0;height:0; }

<强> JS

/**
 * rotatePage
 * Use isMobile() and isPortrait() to toggle classes, set w/h
 */
var rotatePage = function() {
    if ( isMobile() && !isPortrait() ) {
        console.log('Landscape')
        document.body.classList.add('rotate')

        document.getElementsByTagName('html')[0].style.height = window.innerHeight + 'px'
        document.body.style.height = window.innerHeight + 'px'
    }
    if ( isMobile() && isPortrait() ) {
        console.log('Portrait')
        document.body.classList.remove('rotate')

        document.getElementsByTagName('html')[0].style.height = 'auto'
        document.body.style.height = 'auto'
    }
}

/**
 * isPortrait
 * Check if viewport is in portrait by comparing window height/width
 * 
 * @return {Boolean}
 */
var isPortrait = function() {
    if ( window.innerHeight > window.innerWidth ) {
        return true;
    } else {
        return false;
    }
}

/**
 * isMobile
 * Check if the useragent string to verify mobile
 * 
 * @return {Boolean}
 */
var isMobile = function() {
    return (/Mobile|Android|iPhone|iPod|BlackBerry|Windows Phone/i).test(navigator.userAgent || navigator.vendor || window.opera) ? true : false;
}


/**
 * Event Listeners
 */
document.addEventListener('DOMContentLoaded', rotatePage())
window.addEventListener('resize', rotatePage())