`
zhangyaochun
  • 浏览: 2567676 次
  • 性别: Icon_minigender_1
  • 来自: 北京
文章分类
社区版块
存档分类
最新评论

jqm源码分析media

阅读更多

jqm源码系列$.mobile.media

 

  思路分析

 

  • 动态创建一个div,命名为testDiv,设置id为jquery-mediatest,追加到Body中
  • 动态创建一个style,命名为styleBlock,增加一段css规则
//传递一个参数query比如:"only all"
//给上面创建的id为jquery-mediatest设置一个position
"@media " + query + " {#jquery-mediatest{position:absolute;}}"; 

 

  • 插入到html里面,再调用css获取position属性的值是否是absolute
  • 存储到cache对象中,key就是query
  • 注意add的使用,删除动态创建的body和style

 

  TODO:

 

 

 

(function($,undefined){
       //定义变量   
       var $window = $(window),
             $html = $("html");

       $.mobile.media = (function(){
               
              var cache = {},
                    testDiv = $("<div id='jquery-mediatest'></div>"),
                    fakeBody = $("<body>").append(testDiv);
 
              return function(query){
                    if(!(query in cache)){
                          //创建一个style对象取名styleBlock
                          var styleBlock = document.createElement("style"),
                                cssrule = "@media " + query + " {#jquery-mediatest{position:absolute;}}";

                          //IE必须设置type
                          styleBlock.type = "text/css";
                          //初始创建的styleBlock.styleSheet返回的undefined
                          if(styleBlock.styleSheet){

                          }else{
                                 //createTextNode创建文本节点,然后追加到styleBlock里面去
                                 styleBlock.appendChild(document.createTextNode(cssrule))
                          }

                           //把fakeBody追加到html,再把styleBlock追加到html
                           $html.prepend(fakeBody).prepend(styleBlock);

                           //获取一下testDiv的position是否是absolute
                           //cache[query]存储的是true或者false
                           cache[query] = testDiv.css("position") === "absolute";

                           //记得删除styleBlock
                           fakeBody.add(styleBlock).remove();
                            

                    }

                     //返回true或者false
                     return cache[query];
              };

       })();

})(jQuery);
 

 

 

  上一个部分流程的图:

 


      
 

 

 

  • 大小: 20.3 KB
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics