在JS中給元素設置樣式屬性值,只能通過curEle.style.[attr]=value;
這種方式給當前元素設置行內樣式
setCss:給當前元素的某一個樣式屬性設置值(增加在行內樣式上的)
function setCss(curEle,attr,value){
//在JS中設置float樣式值的話也需要處理兼容
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|bottom|left|right|((margin|padding)(Top|Bottom|Left|Right)?))$/;
if(reg.test(attr)){
if(!isNan(value)){//--->判斷傳遞進來的value值是否是一個有效數字,如果是有效數字,證明當前傳遞進來的值沒有加單位,給補充單位
value+=“px”;
}
}
//對于某些樣式屬性,如果傳遞進來的值沒有加單位,需要把單位默認的補充上
curEle["style"][attr]=value;
}
setGroupCss:批量設置元素樣式值
function setGroupCss(curEle,options){
//通過檢測options的數據類型,如果不是一個對象,則不能進行批量設置
if(Object.prototype.toString.call(options)!=="[object Object]"){
return;
}
//遍歷對象中的每一項,調取setCss方法一個個的進行設置即可
for(var key in options){
if(options.hasOwnProperty(key)){ //一般for-in遍歷都是遍歷私有屬性
this.setCss(curEle,key,options[key]);
}
}
}
css:jquery中提供了這樣一個方法,即可以實現獲取,也可以實現單獨設置和批量設置
function css(curEle){
var argTwo=arguments[1];
if(typeof argTwo==="string"){ //第二個參數值是一個字符串,這樣很有可能是獲取樣式;接下來還需判斷是否存在第三個參數,若存在即為單獨設置樣式
var argThree=arguments[2];
if(typeof argThree==="undefined"){ //第三個參數不存在
return this.getCss(curEle,argTwo);
}
//第三個參數存在即為單獨設置
this.setCss(curEle,argTwo,argThree);
}
argTwo= argTwo || 0;
if(argTwo.toString()==="[object Object]"){
this.setGroupCss(curEle,argTwo);
}
}