原生JavaScript操作CSS类名className——hasClass,addClass,removeClass
验证当前元素是否包含className这个类名
function hasClass(curEle, className) {
var reg = new RegExp("(^| +)" + className + "( +|$)");
return reg.test(curEle.className);
}
给元素添加样式类名
function addClass(curEle, className) {
var arr = className.replace(/(^ +| +$)/g, "").split(/ +/g);
for (var i = 0,len=className.length; i < len; i++) {
var curName = arr[i];
if (!hasClass(curEle, className)) {
curEle.className += " " + curName;
}
}
}
移除类名
function removeClass(curEle, className) {
var arr = className.replace(/(^ +| +$)/g, "").split(/ +/g);
for (var i = 0, len = className.length; i < len; i++) {
var curName = arr[i];
if (hasClass(curEle, curName)) {
var reg = new RegExp("(^| +)" + curName + "( +|$)", "g");
curEle.className = curEle.className.replace(reg, " ");
}
}
}