使用jQuery/JavaScript旋转移动设备屏幕

4

如何在点击按钮时更改移动屏幕的方向?比如从竖屏切换到横屏。


请查看此链接:http://www.noupe.com/design/html5-screen-orientation-api-uses-javascript-to-rotate-the-screen-89639.html - Marcos Alexandre Sedrez
这也可能会有帮助:https://dev59.com/R2Yq5IYBdhLWcg3wmRoC - Pete
3个回答

5
您可以使用CSS属性-webkit-transform来改变方向:
if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {
    $('body').css({
        "-webkit-transform": "rotate(90deg)"
    }); 
}

1

我认为移动设备的旋转需要添加一个事件监听器来处理screen.orientation.lock错误。

.main-app是标签的类。

在你的HTML代码中添加一个按钮,例如:

    <div id="lock-landscape-btn" class="hidden">Lock</div>
    <div id="unlock-orientation" class="hidden">unLock</div>

在您的JS代码/文件中添加一个EventListener,例如:
    function rotateScreen () {

        document.querySelector('#lock-landscape-btn').addEventListener('click', function () {

            if( /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) ) {

                if(document.querySelector(".main-app").requestFullscreen) {
                    document.querySelector(".main-app").requestFullscreen();
                }else if(document.querySelector(".main-app").webkitRequestFullScreen) {
                    document.querySelector(".main-app").webkitRequestFullScreen();
                }

                screen.orientation.lock("landscape-primary")
                    .then(function() {
                        console.log('landscape-primary');
                    })
                    .catch(function(error) {
                        console.log(error);
                    });
            }

        });

        document.querySelector("#unlock-orientation").addEventListener('click', function() {
            screen.orientation.unlock();
        });
    };

1
首先使页面全屏。你可以通过以下方式实现:

document.body.requestFullscreen().then(res=>console.log(res).catch(err=>console.log(err);

然后通过使用旋转它。
screen.orientation.lock('landscape').then(res=>console.log(res)).catch(err=>console.log(err))

注意:此方法仅适用于移动浏览器。如果您不知道如何在Android Chrome中使用控制台,请阅读这篇文章

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接