判断横竖屏

css判断横竖屏

        /*orientation:portrait|landscape*/
        /*肖像(竖屏)模式*/
        @media only screen and (orientation: portrait) {
            body {
                background-color: skyblue;
            }
        }

        /*全景模式*/
        @media screen and (orientation: landscape) {
            body {
                background-color: red;
            }
        }    
View Code

js判断横竖屏

 1     // 监听横竖屏状态,发生变化,执行一次回调函数
 2     screen.orientation.addEventListener('change', function (e) {
 3         console.log(e)
 4         isHorizontalOrVertical()
 5     })
 6 
 7     // 判断当前屏幕是横屏还是竖屏(函数调用一次可判断一次)
 8     function isHorizontalOrVertical() {
 9         const orientation = (screen.orientation || {}).type || screen.mozOrientation || screen.msOrientation;
10 
11         if (orientation === "landscape-primary" || orientation === "landscape-secondary") {
12             console.log("That looks good."); //针对横屏
13         } else if (orientation === "portrait-secondary" || orientation === "portrait-primary") {
14             console.log("Mmmh... you should rotate your device to landscape");  //针对竖屏
15         } else if (orientation === undefined) {
16             console.log("The orientation API isn't supported in this browser :("); //判断浏览器是否支持该api
17         }
18     }
View Code

 

posted @ 2021-09-26 15:30  亦茫茫  阅读(25)  评论(0编辑  收藏  举报