mobile设备的横竖屏切换检测

orientationchange Event

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

  1. // Listen for orientation changes
  2. window.addEventListener("orientationchange", function() {
  3. // Announce the new orientation number
  4. alert(window.orientation);
  5. alert(window.outerWidth);
  6. alert(innerWidth);
  7. }, 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: 检测的是pixel

    window.matchMedia

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

  1. // Find matches
  2. var mql = window.matchMedia("(orientation: portrait)");
  3. // If there are matches, we're in portrait
  4. if(mql.matches) {
  5. // Portrait orientation
  6. } else {
  7. // Landscape orientation
  8. }
  9. // Add a media query change listener
  10. mql.addListener(function(m) {
  11. if(m.matches) {
  12. // Changed to portrait
  13. }
  14. else {
  15. // Changed to landscape
  16. }
  17. });

Media Query

使用css媒体查询:

  1. /* portrait */
  2. @media screen and (orientation:portrait) {
  3. /* portrait-specific styles */
  4. }
  5. /* landscape */
  6. @media screen and (orientation:landscape) {
  7. /* landscape-specific styles */
  8. }

参考资料

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