Home > Web Front-end > JS Tutorial > js--How to operate the style class name of an element

js--How to operate the style class name of an element

巴扎黑
Release: 2017-07-22 15:35:12
Original
1158 people have browsed it

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);
    }
Copy after login

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;
            }
        }
        
    }
Copy after login

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," ")
            }
        }
    }
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template