时间:2021-07-01 10:21:17 帮助过:13人阅读
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:给元素增加样式类名
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:给元素移除样式类名
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," ") } } }
以上就是js--怎样去操作元素的样式类名的详细内容,更多请关注Gxl网其它相关文章!