Skip to content
文章目录

屏幕旋转事件

响应屏幕旋转

js
window.addEventListener('orientationchange', function () {
  console.log('the orientation of the device is now ' + screen.orientation.angle)
})

屏幕旋转之后获取 dom 节点大小变化

js
window.addEventListener('orientationchange', function () {
  setTimeout(() => {
    // 在这里获取旋转之后的dom节点变化
  }, 360)
})

在 iphone 中,事件触发后,获取到的屏幕尺寸是改变后的,而在 android(不确定是否全部)中,获取的尺寸是改变前的,大多情况下这并不是我们想要的

解决办法:

可以设置 setTimeout 在 300ms 后获取

判断是横屏还是竖屏

js
// 判断横竖屏
let width = document.documentElement.clientWidth
let height = document.documentElement.clientHeight
if (width > height) {
  alert('横屏')
}

参考资料

MDN: orientationchange

onorientationchange 事件的问题

移动端——orientationchange 事件

H5 + vue 监听手机屏幕旋转及判断横竖屏

js 监听屏幕旋转变化(横屏/竖屏)