标签:
1、hasClass
function hasClass(elem, cls){ cls = cls || ‘‘; if(cls.replace(/\s/g, ‘‘).length == 0) return false; return new RegExp(‘ ‘ + cls + ‘ ‘).test(‘ ‘ + elem.className + ‘ ‘); }
2、addClass
function addClass(elem, cls){ if(!hasClass(elem, cls)){ elem.className += ‘ ‘ + cls; } }
3、removeClass
function removeClass(elem, 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, ‘‘); } }
//call the functions
addClass(document.getElementById("test"), "test");
removeClass(document.getElementById("test"), "test")
if(hasClass(document.getElementById("test"), "test")){//do something};
原生JS实现hasClass,addClass,removeClass
标签:
原文地址:http://www.cnblogs.com/wsir/p/5553720.html