JavaScript获取,设置CSS属性值
1. getCSS方法获取元素样式值
var flag = "getComputedStyle" in window;
function getCSS (curEle, attr) {
var val = null , reg = null ;
if (flag) {
val = window.getComputedStyle(curEle, null )[attr];
} else {
val = curEle.currentStyle[attr];
}
reg = /^(-?\d+(\.\d+)?)(px|pt|rem|em)?$/i ;
return reg.test(val) ? parseFloat (val) : val;
}
2.setCSS方法设置样式属性
function setCSS(curEle, attr, value ) {
if (attr === "float" ) {
curEle['style' ]["cssFloat" ] = value ;
curEle['style' ]["styleFloat" ] = value ;
return ;
}
if (attr === "opacity" ) {
curEle['style' ]["opacity" ] = value ;
curEle['style' ]["filter" ] = "alpha(opacity=" + value * 100 + ")" ;
return ;
}
var reg = /^(width|height|top|right|left|bottom|((margin|padding)(Top|Right|Bottom|Left)?))$/;
if (reg.test(attr)) {
if (!isNaN(value )) {
value += "px" ;
}
}
curEle['style' ][attr] = value ;
}
3.setGroupCss方法批量设置样式属性
function setGroupCss (curEle, options) {
options = options || 0 ;
if (options.toString() !== "[object Object]" ) {
return ;
}
for (var key in options) {
if (options.hasOwnProperty(key)) {
setCSS(curEle, key, options[key]);
}
}
}
4.css 融合上面三个方法,可获取、单独设置、批量设置元素样式值
function css (curEle) {
var arr = Array .prototype.slice.call(arguments ,1 );
var argTwo = arguments [1 ];
if (typeof argTwo === 'string' ) {
if (typeof arguments [2 ] === 'undefined' ) {
return getCSS.apply(curEle, arr);
}
setCSS.apply(curEle, arr);
}
argTwo = argTwo || 0 ;
if (argTwo.toString() === '[object Object]' ) {
setGroupCss.apply(curEle, arr);
}
}