移动端判断横屏竖屏

[javascript] view plain copy
 
  1. 可能我们在写移动端项目的时候会有要求或者为了更好的体验会做<span style="font-size:18px;"><strong>横竖屏检测</strong></span>,以达到更好的用户体验。  
[javascript] view plain copy
 
  1.   
[javascript] view plain copy
 
  1. // 判断横竖屏  
  2. var utils = {  
  3.     debounce: function(func,delay){  
  4.         var timer = null;  
  5.         return function(){  
  6.             var context = this,  
  7.                 args = arguments;  
  8.             clearTimeout(timer);  
  9.             timer = setTimeout(function(){  
  10.                 func.apply(context,args);  
  11.             },delay);  
  12.         }  
  13.     }  
  14. }  
  15. var detectRes = document.getElementById('J_detectRes');  
  16. var detectData = document.getElementById('J_detectData');  
  17. function detectOrient() {  
  18.     var storage = localStorage; // 不一定要使用localStorage,其他存储数据的手段都可以  
  19.     var data = storage.getItem('J-recordOrientX');  
  20.     var cw = document.documentElement.clientWidth;  
  21.     var _Width = 0,  
  22.         _Height = 0;  
  23.     if(!data) {  
  24.         sw = window.screen.width;  
  25.         sh = window.screen.height;  
  26.         // 2.在某些机型(如华为P9)下出现 srceen.width/height 值交换,所以进行大小值比较判断  
  27.         _Width = sw < sh ? sw : sh;  
  28.         _Height = sw >= sh ? sw : sh;  
  29.         storage.setItem('J-recordOrientX',_Width + ',' + _Height);  
  30.     }else {  
  31.         var str = data.split(',');  
  32.         _Width = str[0];  
  33.         _Height = str[1];  
  34.     }  
  35.     if(cw == _Width) {  
  36.         // 竖屏  
  37.         return;  
  38.     }  
  39.     if(cw == _Height){  
  40.         // 横屏  
  41.         return;  
  42.     }  
  43. }  
  44. // 3.函数去抖处理  
  45. window.onresize = utils.debounce(detectOrient,300);  
  46. detectOrient();  
[javascript] view plain copy
 
  1.   
[javascript] view plain copy
 
  1.   
[javascript] view plain copy
 
  1. 详细介绍请参考原作者文章 <a target="_blank" href="http://jdc.jd.com/archives/3862" title="探讨判断横竖屏的最佳实现" style="font-family: "PingFang SC", Verdana, "Helvetica Neue", "Microsoft Yahei", "Hiragino Sans GB", "Microsoft Sans Serif", "WenQuanYi Micro Hei", sans-serif; font-size: 28px; text-decoration-line: none; color: rgb(255, 51, 68);">探讨判断横竖屏的最佳实现</a>  
posted @ 2017-11-04 09:58  五艺  阅读(183)  评论(0)    收藏  举报