Home > Web Front-end > JS Tutorial > Implementation code sharing for adding and removing JavaScript class names

Implementation code sharing for adding and removing JavaScript class names

黄舟
Release: 2017-04-24 09:09:43
Original
1533 people have browsed it

本文给大家分享javascript实现类名的添加与移除功能,需要的朋友参考下吧

方法1:使用className属性

方法2:使用classList API

//用于匹配类名存在与否
function reg(name){
 return new RegExp('(^|\\s)'+name+'(\\s+|$)');
}
//hasClass addClass removeClass toogleClass
var hasClass,addClass,removeClass;
if('classList' in document.documentElement){
 hasClass=function(obj,cname){
  return obj.classList.contains(cname);
 };
 addClass=function(obj,cname){
  obj.classList.add(cname);
 };
 removeClass=function(obj,cname){
  obj.classList.remove(cname);
 };
 toggleClass=function(obj,cname){
  obj.classList.toggle(cname);
 };
}else{
 hasClass=function(obj,cname){
  return reg(cname).test(obj.className);
 };
 addClass=function(obj,cname){
  if(!hasClass(obj,cname)){
   obj.className=obj.className+' '+cname; 
  }
 };
 removeClass=function(obj,cname){
  obj.className=obj.className.replace(reg(cname),' ');
 };
 toggleClass=function(obj,cname){
  var toggle=hasClass(obj,cname)?removeClass:addClass;
  toggle(obj,cname);
 };
}
//true
document.body.classList.toString() === document.body.className;
Copy after login

注意:这种方法每次只能传一个类名且不能级联操作,而jquery下面的类似操作是可以操作多个类名的。

所以扩展一下:

//addClass
DOMTokenList.prototype.addClass=function(str){
 tts.split(' ').forEach(function(c){
 this.add(c);
 }.bind(this));
 return this;
}
//removeClass
DOMTokenList.prototype.removeClass=function(str){
 tts.split(' ').forEach(function(t){
 this.remove(t);
 }.bind(this));
 return this;
}
//removeClass
DOMTokenList.prototype.toggleClass=function(str){
 tts.split(' ').forEach(function(t){
 this.toggle(t);
 }.bind(this));
 return this;
}
Copy after login

The above is the detailed content of Implementation code sharing for adding and removing JavaScript class names. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template