移动端横竖屏判断

1,037 阅读1分钟

CSS Media Queries

通过媒体查询的方式,我们可以通过以下方法来实现根据横竖屏不同的情况来适配样式:

1. 内联样式

@media screen and (orientation:portrait) {
    //竖屏
}

@media screen and (orientation:landscape) {
    //横屏
}

2.外联样式

<!-- 竖屏 -->
<link rel="stylesheet" media="all and (orientation:portrait)" href="..." />

<!-- 横屏 -->
<link rel="stylesheet" media="all and (orientation:landscape)" href="..." />

window.matchMedia()

  1. window.matchMedia()方法接受一个Media Queries语句的字符串作为参数,返回一个MediaQueryList对象。该对象有mediamatches两个属性:
    • 属性media:返回所查询的Media Queries语句字符串
    • 属性matches:返回一个布尔值,表示当前环境是否匹配查询语句
  2. 同时包含两个方法,用来监听事件:
    • addListener(callback):绑定回调callback函数
    • removeListener(callback):注销回调callback函数
var mql = window.matchMedia("(orientation: portrait)");
function onMatchMeidaChange(mql){
  if(mql.matches) {
      // 竖屏
      console.log('竖屏')
  }else {
      // 横屏
      console.log('横屏')
  }
}
onMatchMeidaChange(mql);
mql.addListener(onMatchMeidaChange);

window.innerHeight/window.innerWidth

var utils = {
    debounce: function(func,delay){
        var timer = null;
        return function(){
            var context = this,
                args = arguments;
            clearTimeout(timer);
            timer = setTimeout(function(){
                func.apply(context,args);
            },delay);
        }
    }
}
function detectOrient(){
    // 页面高度大于宽度则是竖屏
    if(window.innerHeight >= window.innerWidth) {
        // 竖屏
    }else {
        // 横屏 
    }
}
detectOrient();
// 在浏览器中,会多次触发resize事件
window.addEventListener('resize',utils.debounce(detectOrient, 300));

window.orientation

MDN上不推荐使用,可能从web标准中移除掉

  1. window.orientation的取值如下
    • 0 代表此时是默认屏幕方向
    • 90 代表顺时针偏离默认屏幕方向90度
    • -90 代表逆时针偏离默认屏幕方向90度
    • 180 代表偏离默认屏幕方向180度
// 简化判断
function detectOrient(){
    if (Math.abs(window.orientation) === 90) {
        // 横屏
    } else {
        // 竖屏
    }
}
detectOrient();
window.addEventListener('orientationchange',detectOrient);