<script> window.onload = function() { var oDiv = document.getElementById(‘div1‘); var oDiv2 = document.getElementById(‘div2‘); addClass(oDiv,‘box1‘); removeClass(oDiv2,‘box‘); function addClass(obj,className) { //如果原来没有Class if(obj.className == ‘‘){ obj.className = className; } else{ //如果原来有class var arrClassName = obj.className.split(‘ ‘); var _index = arrIndexOf(arrClassName,className); if(_index == -1) { //如果要添加的class在原来的class中不存在 obj.className += ‘ ‘ + className; } //如果要添加的class在原来的class中存在 } }; function removeClass(obj,className) { //如果原来有class if(obj.className !=‘ ‘) { var arrClassName = obj.className.split(‘ ‘); var _index = arrIndexOf(arrClassName,className); //如果有我要移除的class if(_index != -1) { arrClassName.splice(_index,1); obj.className = arrClassName.join(‘ ‘); } } //如果原来没有class就什么都不做 }; function arrIndexOf(arr,v) { for(var i=0;i<arr.length;i++) { if(arr[i] == v) { return i; } } return -1; }; }; </script> <body> <div id="div1" class="box">aaaa</div> <div id="div2" class="box">bbb</div> </body>
时间: 2024-10-31 01:42:39