Javascript YUI 读码日记之 YAHOO.util.Dom - Part.3

2018-09-24 21:41

阅读:484

  varpatterns={
HYPHEN:/(-[a-z])/i,
ROOT_TAG:/^bodyhtml$/i
};

vartoCamel=function(property){
//如果没有-[a-z]字母,则直接返回
if(!patterns.HYPHEN.test(property)){
returnproperty;
}

//如果有缓存,直接返回替换后的值
if(propertyCache[property]){
returnpropertyCache[property];
}

//使用正则替换
varconverted=property;
while(patterns.HYPHEN.exec(converted)){
converted=converted.replace(RegExp.$1,
RegExp.$1.substr(1).toUpperCase());
}

//存入缓存
propertyCache[property]=converted;
returnconverted;
};在YAHOO.util.Dom中,getStyle函数考虑了更多不同浏览器兼容性方面的问题,代码如下

//使用W3CDOM标准的浏览器,比如Firefox、Opera、Safari
if(document.defaultView&&document.defaultView.getComputedStyle){
getStyle=function(el,property){
varvalue=null;

//重命名部分CSS样式名
if(property==float){
property=cssFloat;
}

//获取通过CSS加上去的属性
varcomputed=document.defaultView.getComputedStyle(el,);
if(computed){
value=computed[toCamel(property)];
}

returnel.style[property]value;
};
//如果是IE浏览器
}elseif(document.documentElement.currentStyle&&isIE){
getStyle=function(el,property){
switch(toCamel(property)){
//“转换”名称为IE可以认识的
caseopacity:
varval=100;
try{
val=
el.filters[DXImageTransform.Microsoft.Alpha].opacity;
}catch(e){
try{
val=el.filters(alpha).opacity;
}catch(e){
}
}
//百分比
returnval/100;
casefloat:
property=styleFloat;
default:
varvalue=el.currentStyle?el.currentStyle[property]:null;
return(el.style[property]value);
}
};
}else{
//获取内联样式
getStyle=function(el,property){returnel.style[property];};
}另外,PPK在他的Blog上的有关getStyle的阐述,也很精彩,有兴趣的可以去看下。


评论


亲,登录后才可以留言!