原生js仿jquery的css()、hasClass()、addClass()和removeClass()方法:
//css()
Object.prototype.css = function(){
if(arguments.length==1){
return eval("this.style."+arguments[0]);
}else if(arguments.length==2){
eval("this.style."+arguments[0]+"='"+arguments[1]+"'");
return this;
}
};
//hasClass()
Object.prototype.hasClass = function(cName){
return !!this.className.match( new RegExp( "(\\s|^)" + cName + "(\\s|$)") );
}
//addClass()
Object.prototype.addClass = function(cName){
if( !this.hasClass( cName ) ){
this.className += " " + cName;
}
return this;
}
//removeClass()
Object.prototype.removeClass = function(cName){
if( this.hasClass( cName ) ){
this.className = this.className.replace( new RegExp( "(\\s|^)" + cName + "(\\s|$)" )," " );
}
return this;
}
利用html5新API classList及contains实现,但不兼容旧浏览器:
Object.prototype.hasClass = function(cName){
return this.classList.contains(cName)
}
Object.prototype.addClass = function(cName){
if( !this.hasClass( cName ) ){
this.classList.add(cName);
}
return this;
}
Object.prototype.removeClass = function(cName){
if( this.hasClass( cName ) ){
this.classList.remove(cName);
}
return this;
}
以上就是知道不整理的《原生js仿jquery的css()、hasClass()、addClass()和removeClass()方法》,希望对您有所帮助。