下面是一段使用jquery为style属性设置重要参数的sn-p代码。
$.fn.setFixedStyle = function(styles){
var s = $(this).attr("style");
s = "{"+s.replace(/;/g,",").replace(/'|"/g,"");
s = s.substring(0,s.length-1)+"}";
s = s.replace(/,/g,"\",\"").replace(/{/g,"{\"").replace(/}/g,"\"}").replace(/:/g,"\":\"");
var stOb = JSON.parse(s),st;
if(!styles){
$.each(stOb,function(k,v){
stOb[k] +=" !important";
});
}
else{
$.each(styles,function(k,v){
if(v.length>0){
stOb[k] = v+" !important";
}else{
stOb[k] += " !important";
}
});
}
var ns = JSON.stringify(stOb);
$(this).attr("style",ns.replace(/"|{|}/g,"").replace(/,/g,";"));
};
使用非常简单。只需传递一个包含您想要设置为重要属性的所有属性的对象。
$("#i1").setFixedStyle({"width":"50px","height":""});
还有两个附加选项。
1.仅添加重要参数到已经存在的样式属性传递空字符串。
2.为所有存在的属性添加重要参数,不要传递任何东西。它将所有属性设置为重要。
这里是实战。 http://codepen.io/agaase/pen/nkvjr