封装在utils工具函数文件里
let utils = function(){
let getCss = function(curEle,attr){
if(window.getComputedStyle === undefined){return}
let value = window.getComputedStyle(curEle,null)[attr],
reg = /-?\d+(\.\d+)?(px|rem|em|pt)/i;
//过滤是否为纯数字或者数字+单位,使用parseFloat拿到数值
reg.test(value)?value = parseFloat(value):null;
return value;Ï
}
let setCss = function(curEle,attr,value){
if(attr === 'opacity'){
curEle['style'].opacity = value;
curEle['style'].filter =`alpha(opacity=${value*10})`;
return;
}
if(!isNaN(value)){
let reg = /^(width|height|fontSize|(margin|padding)?(top|left|right|bottom)?)$/i;
reg.test(attr)?value+='px':null;
}
curEle['style'][attr] = value;
}
let setGroupCss = function(curEle,options={}){
for(let key in options){
if(!options.hasOwnProperty(key)) continue;
setCss(curEle,key,options[key]);
}
}
let css = function(...arg){
let len = arg.length,second = arg[1],fn = getCss;
len>=3?fn = setCss:null;
len===2&&second instanceof Object&& second !=null ? fn=setGroupCss : null;
return fn(...arg);
}
return{ css }
}()
//使用
utils.css(document.body,{background:“red”,height:200})