移動端豎屏/橫屏判斷

根據 window.orientation 判斷移動設備處於橫屏(landscape)/豎屏(portrait)html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta name="renderer" content="webkit">
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1,user-scalable=no">
    <!-- uc強制豎屏 -->
    <meta name="screen-orientation" content="portrait">
    <!-- QQ強制豎屏 -->
    <meta name="x5-orientation" content="portrait">
    <title>Document</title>
</head>

<body>
    <p>測試橫豎屏</p>
    <script>
        if(window.orientation !== undefined) {
            function checkOrient () {
                if (window.orientation == 0 || window.orientation == 180) {
                    var screenOrientation = 'portrait';
                } else if (window.orientation == 90 || window.orientation == -90) {
                    var screenOrientation = 'landscape';
                }
                return screenOrientation;
            }
            function landscapeAction () {
                if(checkOrient() === 'landscape') {
                    alert('爲了更好的體驗,請選擇豎屏瀏覽!');
                }
            }
            // 添加事件監聽
            addEventListener('DOMContentLoaded', function () {
                landscapeAction();
                window.onorientationchange = landscapeAction;
            });
        }
        
    </script>
</body>

</html>
相關文章
相關標籤/搜索