[TOC]
  • mobile设备的横竖屏切换检测orientationchange Eventresize Eventwindow.matchMediaMedia Query参考资料

mobile设备的横竖屏切换检测

orientationchange Event

我们可以选择在window对象上监听orientationchange属性。比如:

// Listen for orientation changeswindow.addEventListener("orientationchange", function() {    // Announce the new orientation number    alert(window.orientation);    alert(window.outerWidth);    alert(innerWidth);}, false);

window.orientation的取值:

  • 0: portrait
  • 90: landscape rotated to the left
  • -90: landscape rotated to the right
  • 180: portrait, ipad下才能取到resize Event

设备旋转的时候,window的resize事件也是被触发的。判断的方法是:

  • outerWidth, outerHeight: 检测是point
  • innerWidth, innerHeight: 检测的是pixelwindow.matchMedia

这是一段JS代码,可以查询对应的css媒体查询语句是否匹配。

// Find matchesvar mql = window.matchMedia("(orientation: portrait)");// If there are matches, we're in portraitif(mql.matches) {      // Portrait orientation} else {      // Landscape orientation}// Add a media query change listenermql.addListener(function(m) {    if(m.matches) {        // Changed to portrait    }    else {        // Changed to landscape    }});

Media Query

使用css媒体查询:

/* portrait */@media screen and (orientation:portrait) {    /* portrait-specific styles */}/* landscape */@media screen and (orientation:landscape) {    /* landscape-specific styles */}

参考资料

  • Detect Orientation Change on Mobile Devices

原文: https://leohxj.gitbooks.io/front-end-database/content/problems-in-develop-webapp/detect-orientation-change-on-mobile.html