在javascript中使用媒体查询media query

由于需要,我们可能会在js中用到一些media query,从而针对不同的分辨率做一些操作。

 1 //全兼容的 事件绑定  and  阻止默认事件
 2     var EventUtil = {
 3 //Notice: type is not include 'on', for example: click mouseover mouseout and so on
 4         addHandler: function(element, type, handler){
 5             if (element.addEventListener){
 6                 element.addEventListener(type, handler, false);
 7             } else if(element.attachEvent){
 8                 element.attachEvent('on'+type, handler);
 9             } else {
10                 element['on'+type] = handler;
11             }
12         },
13 
14         preventDefault: function(event){
15             if(event.preventDefault){
16                 event.preventDefault();
17             }else{
18                 event.returnValue = false;
19             }
20         }
21     };
22     var mediaQuery = {
23         init:function(){
24             var _this = this;
25             _this.outputSize();
26             EventUtil.addHandler(window,"resize",function(){
27                 _this.outputSize(); //前面的this要单独保存,否则在这里this指的是window
28             });
29         },
30         outputSize:function(){
31             var result1 = window.matchMedia('(min-width:1200px)');
32             var result2 = window.matchMedia('(min-width:992px)');
33             var result3 = window.matchMedia('(min-width:768px)');
34 //console.log(window.innerWidth);
35             //console.log(result.matches);
36             if(result1.matches) {
37                 console.log(">=1200 大型设备 大台式电脑");
38             }else if(result2.matches){
39                 console.log("992=< <=1200 中型设备 台式电脑");
40             }else if(result3.matches){
41                 console.log("768<= <=992 小型设备 平板电脑");
42             }else{
43                 console.log("<=768 超小设备 手机");
44             }
45         }
46     };
47     window.onload = function(){
48         mediaQuery.init();
49     };