JS 检查屏幕方向(横屏还是竖屏)的四种方法

admin 阅读:124 2024-04-02

有时我们制作的一些特殊页面需要检测设备是横屏还是竖屏,然后进行对应的提示。以下是本站总结的 javascript 检查时横屏还是竖屏的四种方法:

一、使用window对象检查屏幕方向

if (window.innerHeight > window.innerWidth) {
  alert("竖屏");
}

if (window.innerHeight < window.innerWidth) {
  alert("横屏");
}

二、使用window.screen对象检查屏幕方向

在移动设备上打开键盘时,window对象方法可能会失效。因此我们可以使用screen.availHeightscreen.availWidth,这样即使在打开键盘后也能获取准确的高度和宽度。

if(screen.availHeight > screen.availWidth){
    alert("竖屏");
}

if(screen.availHeight < screen.availWidth){
    alert("横屏");
}

三、使用screen.orientation.type属性检查屏幕方向

if (
  orientation === "portrait-secondary" ||
  orientation === "portrait-primary"
) {
  alert("竖屏");
}

let orientation = screen.orientation.type;
if (orientation === "landscape-primary") {
  alert("横屏");
}

if (orientation === "landscape-secondary") {
  alert("横屏模式,上下颠倒。");
}

if (orientation === undefined) {
  alert("当前浏览器不支持该方法");
}

screen.orientation.type可能存在兼容性问题,现代浏览器都支持该属性,但老古董设备下可能存在兼容性问题。

四、使用matchMedia方法检查屏幕方向

if (window.matchMedia("(orientation: portrait)").matches) {
  alert("竖屏");
}

if (window.matchMedia("(orientation: landscape)").matches) {
  alert("横屏");
}

screen.orientation.type属性一样,matchMedia方法同样支持较新的浏览器,面对旧设备时可能存在兼容性问题。

声明

1、部分文章来源于网络,仅作为参考。
2、如果网站中图片和文字侵犯了您的版权,请联系1943759704@qq.com处理!