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:
- 没有增加window.matchMedia的原生判断
(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);
上一个部分流程的图:


被折叠的 条评论
为什么被折叠?



