实现toggleClass功能

 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5 <meta charset="UTF-8">
 6 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7 <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8 <title>Document</title>
 9 <style>
10 div.testClass {
11 background-color: gray;
12 }
13 </style>
14 </head>
15 
16 <body>
17 <div id="test" style="width:250px;height:100px;">
18 sssssssssssss
19 </div>
20 <input type="button" value="toggleClassTest" onclick="toggleClassTest();" />
21 </body>
22 
23 
24 <script type="text/javascript">
25 function hasClass(obj, cls) {
26 return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
27 }
28 
29 function addClass(obj, cls) {
30 if (!this.hasClass(obj, cls)) obj.className += " " + cls;
31 }
32 
33 function removeClass(obj, cls) {
34 if (hasClass(obj, cls)) {
35 var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
36 obj.className = obj.className.replace(reg, ' ');
37 }
38 }
39 
40 function toggleClass(obj, cls) {
41 if (hasClass(obj, cls)) {
42 removeClass(obj, cls);
43 } else {
44 addClass(obj, cls);
45 }
46 }
47 
48 function toggleClassTest() {
49 var obj = document.getElementById('test');
50 toggleClass(obj, "testClass");
51 }
52 </script>
53 
54 </html>

 

<!DOCTYPE html>
<html lang="en">

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div.testClass {
background-color: gray;
}
</style>
</head>

<body>
<div id="test" style="width:250px;height:100px;">
sssssssssssss
</div>
<input type="button" value="toggleClassTest" onclick="toggleClassTest();" />
</body>


<script type="text/javascript">
function hasClass(obj, cls) {
return obj.className.match(new RegExp('(\\s|^)' + cls + '(\\s|$)'));
}

function addClass(obj, cls) {
if (!this.hasClass(obj, cls)) obj.className += " " + cls;
}

function removeClass(obj, cls) {
if (hasClass(obj, cls)) {
var reg = new RegExp('(\\s|^)' + cls + '(\\s|$)');
obj.className = obj.className.replace(reg, ' ');
}
}

function toggleClass(obj, cls) {
if (hasClass(obj, cls)) {
removeClass(obj, cls);
} else {
addClass(obj, cls);
}
}

function toggleClassTest() {
var obj = document.getElementById('test');
toggleClass(obj, "testClass");
}
</script>

</html>
posted @ 2017-12-05 15:30  Sunsin  阅读(369)  评论(0编辑  收藏  举报