h5监听resize如何区分键盘弹出和横竖屏切换?

//获取原窗口的高度
let originalHeight = document.documentElement.clientHeight || document.body.clientHeight
window.οnresize = function() {
  //键盘弹起与隐藏都会引起窗口的高度发生变化
  let resizeHeight = document.documentElement.clientHeight || document.body.clientHeight
  if (resizeHeight < originalHeight) {
    //当键盘弹起,在此处操作
  } else {
    //当键盘收起,在此处操作
  }
}

上面是监听输入法弹出的方法,但是h5如果横竖屏切换,也会触发,怎么区分在横竖屏切换时,不做键盘弹出的逻辑?

阅读 1.9k
1 个回答

1.

横屏可以监听orientationchange,

https://developer.mozilla.org/zh-CN/docs/Web/API/Window/orien...
image.png
new Vue({
  el: "#app",
  data() {
    return {
      orientation: '', // 横竖屏标记``,
    }
  },
  created() {
  },
  mounted() {
    this.orient();
    window.addEventListener( 'orientationchange', this.orient);
  },
  methods: {
    orient() {
      if (window.orientation === 90 || window.orientation === -90) {
        //横屏
        this.orientation = 'landscape';
      }
      else if (window.orientation === 0 || window.orientation === 180) {
        //竖屏
        this.orientation = 'portrait';
      }
    },
  }
})

2.

监听resize, 可以根据orientation做判断:

https://developer.mozilla.org/zh-CN/docs/Web/API/Screen/orien...
https://developer.mozilla.org/zh-CN/docs/Web/API/Screen
image.png
mounted() {
      window.addEventListener('resize', this.onWindowResize)
      this.onWindowResize()
}
methods: {
    onWindowResize () {
        var orientation = window.screen.orientation;
        setTimeout(() => {
          this.clientHeight = document.getElementById('app').clientHeight
          this.clientWidth = document.getElementById('app').clientWidth
          setTimeout(() => { // ios需要延时判断
            if (orientation === "landscape-primary") {
                console.log("That looks good.");
              } else if (orientation === "landscape-secondary") {
                console.log("Mmmh... the screen is upside down!");
              } else if (orientation === "portrait-secondary" || orientation === "portrait-primary") {
                console.log("Mmmh... you should rotate your device to landscape");
              } else if (orientation === undefined) {
                console.log("The orientation API isn't supported in this browser :(");
              }
          }, 500)
        }, 0)
      }
}
推荐问题
logo
Microsoft
子站问答
访问
宣传栏