Home >Web Front-end >JS Tutorial >js determines the style className while adding class or deleting class_javascript techniques

js determines the style className while adding class or deleting class_javascript techniques

WBOY
WBOYOriginal
2016-05-16 17:42:381440browse
Copy code The code is as follows:

function MyClass () {}
MyClass.hasClassName = function( element, className)
{
if (!element) return;
var elementClassName = element.className;
if (elementClassName.length == 0) return false;
//Use regular expressions Expression to determine whether there is a real class between multiple classes (processing of leading and trailing spaces)
if (elementClassName == className || elementClassName.match(new RegExp("(^|\s)" className "(\s |$)")))
return true;
return false;
};
MyClass.addClassName = function(element, className)
{
if (!element) return ;
var elementClassName = element.className;
if (elementClassName.length == 0)
{
element.className = elementClassName;
return;
}
if ( elementClassName == className || elementClassName.match(new RegExp("(^|\s)" className "(\s|$)")))
return;
element.className = elementClassName " " className;
};
MyClass.removeClassName = function(element, className)
{
if (!element) return;
var elementClassName = element.className;
if (elementClassName.length == 0) return;
if(elementClassName == className)
{
element.className = "";
return;
}
if (elementClassName.match(new RegExp ("(^|\s)" className "(\s|$)")))
element.className = elementClassName.replace((new RegExp("(^|\s)" className "(\s| $)"))," ");
};
Statement:
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