1. hasClass: Verify whether the current element contains the style class name className
function hasClass(curEle,className){// if(curEle.className.indexOf(className)){// return true; 使用indexOf是有问题的// }// return false;var reg = new RegExp("(^| +)"+className+"( +|$)")return reg.test(curEle.className); }
2. addClass: Add a style class name to the element
function addClass(curEle,className){//为了防止className传递进来的值包含多个样式类名,我们把传递进来的字符串按照一到多个空格拆分成数组中的每一项var ary = className.split(/ +/g);//循环数组,一项项的进行验证增加即可for(var i = 0;i<ary.length;i++){var curName = ary[i]if(!hasClass(curEle,curName)){// curEle.className += " " + className; //如果className类似于这样的"position bg"多个组合的,会出现重复问题curEle.className += " " + curName; } } }
3. removeClass: Remove the style class name to the element
function removeClass(curEle,className){var ary = className.split(/ +/g);for(var i = 0;i<ary.length;i++){var curName = ary[i]if(hasClass(curEle,curName)){var reg = new RegExp("(^| +)"+curName+"( +|$)","g"); curEle.className = curEle.className.replace(reg," ") } } }
The above is the detailed content of js--How to operate the style class name of an element. For more information, please follow other related articles on the PHP Chinese website!