实现DOM classList的add、remove、toggle

function MyClassList(classes, dom){
	[].push.apply(this, classes)
	Object.defineProperty(this, "__value__", {
		enumerable: false,
		set: function(val){
			dom.className = val;
		}
	})
}
MyClassList.prototype = {
	addClass: function addClass(cls){	
		if(!this.contains(cls)){
			[].push.call(this, cls)
		}
		this.__value__ = [].join.call(this, " ")
	},
	removeClass: function removeClass(cls){
		if(this.contains(cls)){
			for(var i=0;i<this.length;i++){
				if(this[i] === cls){
					[].splice.call(this, i, 1)
					return cls;
				}
			}
			this.__value__ = [].join.call(this, " ")
		}
	},
	toggleClass: function toggleClass(cls){
		this.contains(cls) ? this.removeClass(cls) : this.addClass(cls);
		this.__value__ = [].join.call(this, " ")
	},
	contains: function contains(cls){
		return [].includes.call(this, cls)
	}
}
Object.defineProperty(HTMLElement.prototype, "myClassList", {
  get: function(){
	if(!this.__classList__){
		this.__classList__ = new MyClassList(this.className.split(/\s+/),this)
	}
	return this.__classList__;
  }
});

  

div id="myDiv" class="a b c"></div>

  

myDiv.myClassList.addClass("d")	
myDiv.myClassList.removeClass("b")			
myDiv.myClassList.toggleClass("E")	

  实现DOM classList的add、remove、toggle

 

上一篇:简单的div弹出例子


下一篇:深入理解定时器系列第二篇——被誉为神器的requestAnimationFrame