领先的免费Web技术教程,涵盖HTML到ASP.NET

网站首页 > 知识剖析 正文

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

nixiaole 2024-11-15 23:01:38 知识剖析 19 ℃
/**

 * @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的跨浏览器操作*/

Tags:

最近发表
标签列表