发布于 1年前
JS 操作元素样式
const getCss = function getCss(element, attr) { // 元素,属性
let value = window.getComputedStyle(element)[attr],
reg = /^\d+(px|rem|em)?$/i;
if (reg.test(value)) {
value = parseFloat(value);
}
return value;
};
const setCss = function setCss(element, attr, value) {
if (attr === "opacity") { // 元素,属性 ,值
element['style']['opacity'] = value;
element['style']['filter'] = `alpha(opacity=${value*100})`;
return;
}
let reg = /^(width|height|margin|padding)?(top|left|bottom|right)?$/i;
if (reg.test(attr)) {
if (!isNaN(value)) {
value += 'px';
}
}
element['style'][attr] = value;
};
const setGroupCss = function setGroupCss(element, options) {
each(options, (copy, name) => {
setCss(element, name, copy);
});
};
const css = function css(element) {
let len = arguments.length,
attr = arguments[1],
value = arguments[2];
if (len >= 3) {
setCss(element, attr, value);
return;
}
if (attr !== null && typeof attr === "object") {
setGroupCss(element, attr);
return;
}
return getCss(element, attr);
};