龙空技术网

JavaScript-浏览器兼容的脚本化class操作

程序编码jjh 93

前言:

目前同学们对“js元素class”大概比较关心,咱们都想要知道一些“js元素class”的相关资讯。那么小编也在网上网罗了一些有关“js元素class””的相关知识,希望你们能喜欢,同学们快快来学习一下吧!

/** * @author zswxjjh * @date  2021/3/29 */'use  strict';/** 模仿DOMTokenList对象,提供contains()* add(),remove()。toggle()方法* 重写toString方法,为了模拟类数组特性* 提供toArray方法** */var  classList=(function () {  /*  * e是一个元素,定义一个CSSClassList类模拟  * DOMTokenList类  * */  function classList(e) {   /* if(e.classList)      return e.classList;    else*/      return new CSSClassList(e);  }  /*  * 定义CSSClassList类  * */  function CSSClassList(e) {     this.e=e;  }  /*  * c是一个合法的类名,判断是否包含给定的类名  * 返回boolean  * */  CSSClassList.prototype.contains=function (c) {      //是否合法    if(!c)    {      throw new TypeError('参数不存在!');    }    else  if(c.length===0 || c.lastIndexOf(' ')!==-1/*c包含空格*/)    {      throw new TypeError('不合法的类名:"'+c+'"!');    }    if(!this.e.className)      return false;   if(this.e.className===c)     return true;   return this.e.className.search('\\b'+c+'\\b')!==-1;  };  /*  * 追加一个类名在尾部  *  * */  CSSClassList.prototype.add=function (c) {      if(this.contains(c))        return;      //判断值里面是否以空格结尾      var classes=this.e.className;       if(!classes)         this.e.className='';       if(classes.length!==0 && classes[classes.length-1]!==' ')/*不是以空格结尾*/       {          c=' '+c;       }       this.e.className+=c;  };  /*  * 移除类名字c  * */  CSSClassList.prototype.remove=function (c) {     if(this.contains(c))     {       var pattern=new RegExp('\\b'+c+'\\b\\s*','g');       this.e.className=this.e.className.replace(pattern,'');       if(!this.e.className)       {         this.e.removeAttribute('class');       }     }  };  /*  * 如果c存在,删除c,返回false  * 否则,追加c,返回true  * */  CSSClassList.prototype.toggle=function (c) {     if(this.contains(c))     {       this.remove(c);       return false;     }     else     {       this.add(c);       return true;     }  };  /*  * 覆盖toString方法  * */  CSSClassList.prototype.toString=function () {      return this.e.className;  };  /*  * 提供类数组的功能,转换成数组  * */  CSSClassList.prototype.toArray=function () {      return this.e.className.match(/\b\w+\b/g) ||[];  };  return classList;})();/*以上代码提供对HTML5标签属性class的跨浏览器操作*/

标签: #js元素class #js移除class属性 #css移除class #css标签class #js中classlist