ie9中的classList实现

(function(){
  if(document.body.classList == null && Element){
    var wjClassList = {
      el: null,
      names: [],
      getClass: function(){
        var cNames = this.el.className;
        this.names = cNames ? cNames.trim().split(/\s+/) : [];
      },
      genClass: function(){
        this.el.className = this.names.join(" ");
      },
      add:function(cName){
        var i = this.contains(cName);
        if(i === false){
          this.names.push(cName);
          this.genClass();
        }
      },
      remove: function(cName){
        var i = this.contains(cName);
        if(typeof i == "number"){
          this.names[i] = "";
          this.genClass();
        }
      },
      toggle: function(cName){
        var i = this.contains(cName);
        if(i === false){
          this.add(cName);
        }else{
          this.remove(cName);
        }
      },
      contains: function(cName){
        this.getClass();

        var i, len = this.names.length;
        for(i = 0; i < len; i++){
          if(this.names[i] == cName){
            return i; // 如果存在,返回索引
          }
        }
        return false;
      },
    };

    // 在不支持classList的浏览器中, 在Element的原型中写入此方法
    Object.defineProperty(Element.prototype, 'classList', {
      get: function(){
        wjClassList.el = this;
        return wjClassList;
      }
    });
  }
})();

posted @ 2017-11-07 13:39  吴知客  阅读(251)  评论(0编辑  收藏  举报