var Element = {};
Element.getStyles1 = function() {
var view = document.defaultView;
var propCache = {};
var camelRe = /(-[a-z])/gi;
var camelFn = function(m, a) {
return a.charAt(1).toUpperCase();
};
return view && view.getComputedStyle ? function(el, prop) {
var v, cs, camel;
if (prop == 'float') {
prop = "cssFloat";
}
if (v = el.style[prop]) {
return v;
}
if (cs = view.getComputedStyle(el, "")) {
//if (!(camel = propCache[prop])) {
//camel = propCache[prop] = prop.replace(camelRe, camelFn);
// }
camel = prop.replace(camelRe, camelFn);
return cs[camel];
}
return null;
} : function(el, prop) {
var v, cs, camel;
if (prop == 'opacity') {
if (typeof el.style.filter == 'string') {
var m = el.style.filter.match(/alpha\(opacity=(.*)\)/i);
if (m) {
var fv = parseFloat(m[1]);
if (!isNaN(fv)) {
return fv ? fv / 100 : 0;
}
}
}
return 1;
} else if (prop == 'float') {
prop = "styleFloat";
}
if (!(camel = propCache[prop])) {
camel = propCache[prop] = prop.replace(camelRe, camelFn);
}
if (v = el.style[camel]) {
return v;
}
if (cs = el.currentStyle) {
return cs[camel];
}
return null;
};
}();
Element.getStyles2 = function(element, style) {
var camelRe = /(-[a-z])/gi;
var propCache = {};
var camelFn = function(m, a) {
return a.charAt(1).toUpperCase();
};
//if (!(camel = propCache[style])) {
camel = propCache[style] = style.replace(camelRe, camelFn);
// }
style = style == 'float' ? 'cssFloat' : camel;//style.replace(camelRe, camelFn);;
var value = element.style[style];
if (!value || value == 'auto') {
if(document.defaultView)
var css = document.defaultView.getComputedStyle(element, null);
value = css ? css[style] : null;
}
if (style == 'opacity')
return value ? parseFloat(value) : 1.0;
return value == 'auto' ? null : value;
};
var s = ['width', 'heigth', 'opacity', 'float', 'margin', 'border',
'background', 'top', 'button','padding-left','padding-right','margin-bottom','border-bottom-width','border-right-width'];
var now = new Date().getTime();
for (var i = 0;i < 10000; i++) {
var m =parseInt(Math.random()*(s.length-1))+1;
var el=document.getElementById('test1');
Element.getStyles1(el, s[m]);
}
var now1 = new Date().getTime();
alert(now1 - now);
var now = new Date().getTime();
for (var i = 0;i < 10000; i++) {
var m =parseInt(Math.random()*(s.length-1))+1;
Element.getStyles2 (document.getElementById('test1'), s[m]);
}
var now1 = new Date().getTime();
alert(now1 - now);
在分析Ext,覺得ext,yui(類似style1的實作)要不要這樣做,于是做了一個性能的測試
在IE中 style1:420-440之間,style2:'453-470之間
在FF中,style1:953-970之間,style2:1266-1287之間
加上came緩存的性能提升在0-20之間。
先不用去說prototype,mootools的類似的getstyle2的實作上有點問題。而且性能還是差很多,要慢五分之一。