判断是否有某个class,如果有就删掉,没有加上 <style> #div1 {width: 100px;height: 100px;position: absolute;} .div1{background:red;} .div2{background:yellow;} </style> <div id="div1" class="div2 div1 div3 div2"></div> <script> var oDiv1 = document.getElementById("div1"); oDiv1.onclick = function() { hasClass(this,"div2") } function hasClass(obj,sClass) { var oldClass = obj.className; var re = new RegExp(‘\\b‘ + sClass + ‘\\b‘); if (re.test(oldClass)) { obj.className=obj.className.split(sClass).join("").replace(/\s+$/,"") } else { obj.className = oldClass +" "+ sClass } } </script>
时间: 2024-10-26 06:08:49