This article is divided into two parts to explain, the specific contents are as follows
The first part: the native JS realizes the Addclass,removeclass,hasclass method
function Hasclass (Elem, CLS) {
cls = CLS | | '';
if (Cls.replace (/\s/g, '). Length = = 0) return false; Returns false to the new RegExp (' + CLS + ') when the CLS has no arguments
. Test (' + Elem.classname + ');
}
function AddClass (ele, CLS) {
if (!hasclass (Elem, CLS)) {
Ele.classname = Ele.classname = = '? cls:ele.classNam E + ' + cls;
}
}
function Removeclass (ele, CLS) {
if (Hasclass (Elem, CLS)) {
var newclass = ' + elem.className.replace (/[\t\r\n ]/g, "') +";
while (Newclass.indexof (' + cls + ') >= 0) {
newclass = newclass.replace (' + cls + ', ');
}
Elem.classname = Newclass.replace (/^\s+|\s+$/g, ');
}
}
Part II: using native JS to implement jquery addclass, Removeclass, Hasclass function
function addclass (obj, cls) {var obj_class = obj.classname,//Gets the class content. Blank = (Obj_class!= ")?
":"//To determine whether the acquired class is empty, and add a ' space ' to the front if it is not empty.
Added = Obj_class + blank + cls;//combines the original class and the class that needs to be added.
Obj.classname = added;//replaces the original class. The function removeclass (obj, cls) {var obj_class = ' +obj.classname+ ';//Gets the class content and adds a space to the end. ex) ' ABC BCD '-& Gt ' abc BCD ' OBJ_CLASS = Obj_class.replace (/(\s+)/gi, '),//replaces extra empty characters with a single space. EX) ' ABC BCD '-> ' abc bcd ' removed = obj_class.replace (' +cls+ ', ');//Replace the class with space in the original class. EX) ' ABC BCD '-> ' bcd ' removed = removed.replace (/(^\s+) | ( \s+$)/g, "")//Remove the trailing space.
Ex) ' BCD '-> ' BCD ' obj.classname = removed;//replaces the original class.
The function hasclass (obj, cls) {var obj_class = obj.classname,//Gets the class content.
Obj_class_lst = Obj_class.split (/\s+/);//The CLS is converted to an array by a split null character.
x = 0;
for (x in Obj_class_lst) {if (obj_class_lst[x] = = CLS) {//loop array, to determine whether CLS return true is included; } returnFalse
}
The above is the entire content of this article, I hope to learn JavaScript program to help you.