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


var patterns = {
HYPHEN: /(-[a-z])/i,
ROOT_TAG: /^body|html$/i
};

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

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

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

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

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

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

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

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

« 
» 
快速导航

Copyright © 2016 phpStudy | 豫ICP备2021030365号-3