在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     };

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM