js设置元素class方法小结及classList相关
给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定义的方法对其进行修改。
add( class1, class2, ...)
在元素中添加一个或多个类名(如果指定的类名已存在,则不会添加)用法:`el.classList.add("a", "b", "c");`remove( class1, class2, ...)
删除元素中一个或多个类名用法:el.classList.remove('a','b');toggle(class, true|false)
在元素中切换类名;参数1:要移出或者添加的类名;参数2:可选参数,不论类名是否存在,为true时强制添加类名,false时强制删除类名;用法: 添加:el.classList.toggle("d", true);删除:el.classList.toggle("d", false);contains( class )
判断指定的类名是否存在;用法:el.classList.contains("e") ,//如果e存在返回trueitem(index)
根据索引返回类名,索引从 0 开始,如果没有则返回null;用法:el.classList.item(0) //返回elength属性var len = document.body.classList.length;
兼容:支持classList属性的浏览器有Firefox 3.6+,ie10+和Chrome。IE9和IE9以前的版本不支持该属性,移动端方面,除了安卓2.3及以下版本的webview不支持,其它浏览器终端都能很好地支持。
最后,给不支持classList的浏览器(ie9及以下等)总结两种兼容解决方案:
第一种:
- if (!("classList" in document.documentElement)) {
- Object.defineProperty(HTMLElement.prototype, 'classList', {
- get: function() {
- var self = this;
- function update(fn) {
- return function(value) {
- var classes = self.className.split(/\s+/g),
- index = classes.indexOf(value);
- fn(classes, index, value);
- self.className = classes.join(" ");
- }
- }
- return {
- add: update(function(classes, index, value) {
- if (!~index) classes.push(value);
- }),
- remove: update(function(classes, index) {
- if (~index) classes.splice(index, 1);
- }),
- toggle: update(function(classes, index, value) {
- if (~index)
- classes.splice(index, 1);
- else
- classes.push(value);
- }),
- contains: function(value) {
- return !!~self.className.split(/\s+/g).indexOf(value);
- },
- item: function(i) {
- return self.className.split(/\s+/g)[i] || null;
- }
- };
- }
- });
- }
第二种:从新写了方法,比前一种代码多点,原文出处
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相关的更多相关文章
- js面向对象 多种创建对象方法小结
转自js面向对象 多种创建对象方法小结 1.对象字面量 var clock={ hour:12, minute:10, second:10, showTime:function(){ alert(th ...
- js设置元素不能编辑
js设置元素不能编辑 $("#startLocation").attr("readOnly",true); js设置元素可以编辑 $("#startL ...
- js设置元素float的问题
用js设置一个元素的float样式 div.style.float = 'left'; 这句话在谷歌浏览器或许没问题,但是在IE,火狐下会无效 正确写法是 div.style.styleFloat = ...
- ***php 数组添加关联元素的方法小结(关联数组添加元素)
我们这里介绍的是在数组中再增加关联数组了,这个就合成了多维数组,下面我来给大家举几个实例,希望对各位同学会有所帮助哈. 在"php 数组添加元素方法总结这篇文章中介绍了如何给数组添加元素,那 ...
- js设置元素的onclick传参方法
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <HTML> <HEAD ...
- js生成随机数的方法小结
js生成随机数主要用到了内置的Math对象的random()方法.用法如:Math.random().它返回的是一个 0 ~ 1 之间的随机数.有了这么一个方法,那生成任意随机数就好理解了.比如实际中 ...
- 使用js获取QueryString的方法小结
一.<script> urlinfo=window.location.href; //获取当前页面的url len=urlinfo.length;//获取url的长度 offset=url ...
- MySQL数据库设置远程访问权限方法小结
http://www.jb51.net/article/42441.htm MySQL基础知识第一期,如何远程访问MySQL数据库设置权限方法总结,讨论访问单个数据库,全部数据库,指定用户访问,设置访 ...
- js设置元素指定时间隐藏
$().fadeOut(); js指定时间隐藏
随机推荐
- svn服务器的搭建与使用一
转载出处 Subversion是优秀的版本控制工具,其具体的的优点和详细介绍,这里就不再多说. 首先来下载和搭建SVN服务器. 现在Subversion已经迁移到apache网站上了,下载地址: ht ...
- 》》jquery-weui 初
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta na ...
- 2.python的文件类型、变量数值和字符串练习
1.python的文件类型 .源代码 -python 源代码文件以"py"为扩展名,由python程序解释,不需要编译. 2.字节代码(编译的) -python源码文件经编译后生成 ...
- BEGINNING SHAREPOINT® 2013 DEVELOPMENT 第8章节--配送SP2013Apps
BEGINNING SHAREPOINT® 2013 DEVELOPMENT 第8章节--配送SP2013Apps 本章节你将学到: 通过SP商店配送Apps: 在商店授予证书并管理A ...
- quick-cocos2d-x教程1:在window上创建第一个项目文件夹,并制作helloworld
说明:此教程是针对cocos2dx 2.0系列的,3.0的版本号,如今还没有公布出来. 1)首先从github.com把这个项目下载到本地.然后装到d盘的根文件夹,并设置文件夹路径为d:\quick- ...
- Android学习笔记(27):日历视图Calendar
日历视图CalendarView可用于显示和选择日期. 能够调用setOnDateChangedListener()方法绑定事件监听器. 经常使用XML属性和相关方法: XML属性 相关方法 说明 a ...
- jQuery 学习笔记(三)——事件与应用
页面载入时触发ready()事件 ready()事件类似于onLoad()事件.但前者仅仅要页面的DOM结构载入后便触发.而后者必须在页面所有元素载入成功才触发,ready()能够写多个,按顺序运行. ...
- iOS 6.0中UIViewController被弃用的一些方法
郝萌主倾心贡献.尊重作者的劳动成果,请勿转载. 假设文章对您有所帮助,欢迎给作者捐赠,支持郝萌主,捐赠数额任意.重在心意^_^ 我要捐赠: 点击捐赠 Cocos2d-X源代码下载:点我传送 概念:de ...
- Lua代码提示和方法跳转
前言 当在一个大型工程中编写大量的lua脚本时,代码提示和方法跳转等功能很实用,据我所了解的目前除LuaStudio之外,似乎还没有一个很好的编辑器.但今天讲述的是Idea +EmmyLua插件 达到 ...
- mybatis 之 占位符#{} 和 ${}
#{}占位符用来设置参数,参数的类型可以有3种,基本类型,自定义类型,map基本类型作为参数,参数与占位符中的名称无关. <select id="findById" para ...