标签:
1、传统方法:
在操作类名的时候,需要通过className属性添加、删除和替换类名。如下面例子:
1
|
<div class = "bd user disabled" >...</div> |
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
<script type= "text/javascript" > var className=div.className.split(/\s+/); //找到要删掉的类名 var pos=- 1 , i,len; for (var i = 0 ; i < className.length; i++) { if (className[i]== "user" ){ pos=i; break ; } }; className.splice(i, 1 ); div.className=className.join( " " ); //将余下的类名重新拼装 </script> |
2、html5新增方法classList(),可以完全摆脱className属性。
具体使用案例如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
<title>classList Example</title> <style> .highlight { background: yellow; } </style> <div id= "myDiv" class = "init" >Hello world!</div> <input type= "button" value= "Add class" onclick= "addClass()" > <input type= "button" value= "Remove class" onclick= "removeClass()" > <input type= "button" value= "Toggle class" onclick= "toggleClass()" > <input type= "button" value= "Contains class?" onclick= "containsClass()" > <p>This demo works in Firefox 3.6 and Chrome 8 .</p> <script type= "text/javascript" > function addClass(){ var myDiv = document.getElementById( "myDiv" ); myDiv.classList.add( "highlight" ); } function removeClass(){ var myDiv = document.getElementById( "myDiv" ); myDiv.classList.remove( "highlight" ); } function toggleClass(){ var myDiv = document.getElementById( "myDiv" ); myDiv.classList.toggle( "highlight" ); } function containsClass(){ var myDiv = document.getElementById( "myDiv" ); alert(myDiv.classList.contains( "highlight" )); } </script> |
参考链接:http://www.2cto.com/kf/201409/331425.html
标签:
原文地址:http://www.cnblogs.com/alicePanZ/p/5135106.html