标签:addclass hasclass removeclass
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, ‘‘); } }
原生JS实现hasClass,addClass,removeClass
标签:addclass hasclass removeclass
原文地址:http://qings.blog.51cto.com/4857138/1562222