给DOM元素设置class是我们在项目中非常容易遇到的,网上的资料和总结也比较多,下面比较全面的整理一下,希望给到大家一些帮助!并引用两种成熟的classList的兼容方法

一、el.setAttribute('class','abc'); 

var div = document.getElementById('d1');
div.setAttribute("class", "abc");

兼容:IE8/9/10/Firefox/Safari/Chrome/Opera支持  IE6/7不支持setAttribute('class',xxx)方式设置元素的class。

二、el.setAttribute('className', 'abc') 

var div = document.getElementById('d1');
div.setAttribute("className",
"abc");

兼容:IE6/7支持  IE8/9/10/Firefox/Safari/Chrome/Opera不支持setAttribute('className',xxx)方式设置元素的class。

三、el.className = 'abc'; 

var div = document.getElementById('d1');
div.className = 'abc';

兼容:所有浏览器都支持。

四、classList属性

HTML5新增的JavaScript API,HTML5为每个元素定义了classLlist属性,用于在元素中添加,移除及切换 CSS 类。该属性是 DOMTokenList 对象(一个只读的类数组对象),你可以通过DOMTokenList定义的方法对其进行修改。

  1. add( class1, class2, ...)    在元素中添加一个或多个类名(如果指定的类名已存在,则不会添加)用法:`el.classList.add("a", "b", "c");`

  2. remove( class1, class2, ...)    删除元素中一个或多个类名用法:el.classList.remove('a','b');          

  3. toggle(class, true|false)    在元素中切换类名;参数1:要移出或者添加的类名;参数2:可选参数,不论类名是否存在,为true时强制添加类名,false时强制删除类名;用法: 添加:el.classList.toggle("d", true);删除:el.classList.toggle("d", false);           

  4. contains( class )    判断指定的类名是否存在;用法:el.classList.contains("e") ,//如果e存在返回true 

  5. item(index)    根据索引返回类名,索引从 0 开始,如果没有则返回null;用法:el.classList.item(0) //返回e

  6. length属性 var len = document.body.classList.length;

兼容:支持classList属性的浏览器有Firefox 3.6+,ie10+和Chrome。IE9和IE9以前的版本不支持该属性,移动端方面,除了安卓2.3及以下版本的webview不支持,其它浏览器终端都能很好地支持。

最后,给不支持classList的浏览器(ie9及以下等)总结两种兼容解决方案:

第一种:

  1. if (!("classList" in document.documentElement)) {
  2. Object.defineProperty(HTMLElement.prototype, 'classList', {
  3. get: function() {
  4. var self = this;
  5. function update(fn) {
  6. return function(value) {
  7. var classes = self.className.split(/\s+/g),
  8. index = classes.indexOf(value);
  9. fn(classes, index, value);
  10. self.className = classes.join(" ");
  11. }
  12. }
  13. return {
  14. add: update(function(classes, index, value) {
  15. if (!~index) classes.push(value);
  16. }),
  17. remove: update(function(classes, index) {
  18. if (~index) classes.splice(index, 1);
  19. }),
  20. toggle: update(function(classes, index, value) {
  21. if (~index)
  22. classes.splice(index, 1);
  23. else
  24. classes.push(value);
  25. }),
  26. contains: function(value) {
  27. return !!~self.className.split(/\s+/g).indexOf(value);
  28. },
  29. item: function(i) {
  30. return self.className.split(/\s+/g)[i] || null;
  31. }
  32. };
  33. }
  34. });
  35. }

第二种:从新写了方法,比前一种代码多点,原文出处

    var classList = null;
(function(){
classList = function (obj){
this.obj = obj;
};
classList.prototype.add = function(value){
if(typeof value !== "string") throw TypeError("the type of value is error");
if(this.obj.classList){
this.obj.classList.add(value);
}else{
var arr = value.replace(/^\s+|\s+$/g,"").split(/\s+/);
this.obj.classList +=" "+arr.join(" ");
}
};
classList.prototype.contains = function(value){
if(typeof value !== "string") throw TypeError("the type of value is error");
if(this.obj.classList){
return this.obj.classList.contains(value);
}else{
var arr = value.replace(/^\s+|\s+$/g,"").split(/\s+/);
var _className = this.obj.className;
for(var i = 0,len= arr.length; i<len; i++){
if(_className.search(new RegExp("(\\s+)?"+arr[i]+"(\\s+)?"))===-1){
return false;
}
}
return true;
}
};
classList.prototype.remove = function(value){
if(typeof value !== "string") throw TypeError("the type of value is error");
if(this.obj.classList){
return this.obj.classList.remove(value);
}else{
var arr = value.replace(/^\s+|\s+$/g,"").split(/\s+/);
var _className = this.obj.className;
for(var i = 0, len = arr.length;i<len; i++){
if(_className.search(new RegExp("(\\s+)?"+arr[i]+"(\\s+)?"))!==-1){
_className = _className.replace(new RegExp("(\\s+)?"+arr[i]+"(\\s+)?"),"");
}
}
this.obj.className = _className;
}
};
classList.prototype.toggle = function(value){
if(typeof value !== "string") throw TypeError("the type of value is error");
if(this.contains(value)){
this.remove(value);
}else{
this.add(value);
}
};
})(); ps:附上张鑫旭博客中关于classList的文章,让你理解的更透彻!
HTML5 DOM元素类名相关操作API classList简介
												

js设置元素class方法小结及classList相关的更多相关文章

  1. js面向对象 多种创建对象方法小结

    转自js面向对象 多种创建对象方法小结 1.对象字面量 var clock={ hour:12, minute:10, second:10, showTime:function(){ alert(th ...

  2. js设置元素不能编辑

    js设置元素不能编辑 $("#startLocation").attr("readOnly",true); js设置元素可以编辑 $("#startL ...

  3. js设置元素float的问题

    用js设置一个元素的float样式 div.style.float = 'left'; 这句话在谷歌浏览器或许没问题,但是在IE,火狐下会无效 正确写法是 div.style.styleFloat = ...

  4. ***php 数组添加关联元素的方法小结(关联数组添加元素)

    我们这里介绍的是在数组中再增加关联数组了,这个就合成了多维数组,下面我来给大家举几个实例,希望对各位同学会有所帮助哈. 在"php 数组添加元素方法总结这篇文章中介绍了如何给数组添加元素,那 ...

  5. js设置元素的onclick传参方法

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD ...

  6. js生成随机数的方法小结

    js生成随机数主要用到了内置的Math对象的random()方法.用法如:Math.random().它返回的是一个 0 ~ 1 之间的随机数.有了这么一个方法,那生成任意随机数就好理解了.比如实际中 ...

  7. 使用js获取QueryString的方法小结

    一.<script> urlinfo=window.location.href; //获取当前页面的url len=urlinfo.length;//获取url的长度 offset=url ...

  8. MySQL数据库设置远程访问权限方法小结

    http://www.jb51.net/article/42441.htm MySQL基础知识第一期,如何远程访问MySQL数据库设置权限方法总结,讨论访问单个数据库,全部数据库,指定用户访问,设置访 ...

  9. js设置元素指定时间隐藏

    $().fadeOut(); js指定时间隐藏

随机推荐

  1. Dynamics CRM可以设置会话超时和非活动超时吗?

    本人微信和易信公众号: 微软动态CRM专家罗勇 ,回复266或者20171213可方便获取本文,同时可以在第一间得到我发布的最新的博文信息,follow me!我的网站是 www.luoyong.me ...

  2. 【Keras】从两个实际任务掌握图像分类

    我们一般用深度学习做图片分类的入门教材都是MNIST或者CIFAR-10,因为数据都是别人准备好的,有的甚至是一个函数就把所有数据都load进来了,所以跑起来都很简单,但是跑完了,好像自己还没掌握图片 ...

  3. AspNet Core Api Restful +Swagger 发布IIS 实现微服务之旅 (二)

    上一步我们创建好CoreApi 接下来在框架中加入 Swagger  并发布  到 IIS (1)首先点击依赖项>管理Nuget包 (2)输入 Swashbuckle.aspnetCore  比 ...

  4. 并发与并行的区别 The differences between Concurrency and Parallel

    逻辑控制流 在程序加载到内存并执行的时候(进程),操作系统会通过让它和其他进程分时段占用CPU(CPU slices)让它产生自己独占CPU的假象(同时通过虚拟内存让它产生独占内存的假象).在CPU在 ...

  5. System.getProperty()方法获取系统变量

    来自我的CSDN博客   今天在阅读JDBC的DriverManager类源码时,看到了这么一句代码: System.getProperty("jdbc.drivers"):    ...

  6. Objective-C基础语法高速入门

    Objective-C是Mac软件开发领域最基本的开发语言,假如我们对C语言已经非常熟悉或者具有面向对象语言的基础.对于我们学习Objective-C将会非常实用. 方法调用(Calling Meth ...

  7. 介绍一个法国的时间戳server

    特别说明: 以下介绍的法国时间戳server已经停止服务了.我曾发Email给相关站点的管理员.对方回复说他也不知道什么时候能恢复服务,有可能就是遥遥无期了.所以以下的内容仅有參考价值.没法实践了. ...

  8. String.prototype.trim

    /*内置对象添加方法:String.prototype.trim(给String添加一个trim方法) *^这个是以什么什么开头 *$这个是以什么什么结尾 *'/s是String /d是数字' *re ...

  9. SharePoint Patterns and Practices 简介

    作者:陈希章 发表于 2017年12月22日 SharePoint Patterns and Practices,以下简称PnP,是由微软的SharePoint产品组发起并主持的一个有关SharePo ...

  10. Mixed Reality-宁波市VR/AR技术应用高研班总结

    年,全球AR与VR市场规模将达到1500亿美元,而根据市场研究机构BI Intelligence的统计,2020年仅头戴式VR硬件市场规模将达到28亿美元,未来5年复合增长率超过100%.本次培训从V ...