<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title></title> <style type="text/css"> {.d1 width: 100px; height: 100px; background-color: red; } .d2{ height: 200px; background-color: green; } </style> </head> <body> <button id="btn">操作#d01</button> <br /><br /> <div id="box" class="d1 d2"> </div> </body> <script type="text/javascript"> var btn=document.getElementById("btn"); var box=document.getElementById("box"); /* * Indirectly by the class attribute to modify the style * We only need to modify the time, improve performance, * / Btn.onclick = function () { // box.className = "d2"; // box.className + = "d2"; // increase in style d2 d1, d2 Note that a space in front of //addClass(box,"d2"); //removeClass(box,"d2"); toggleClass(box,"d2"); } / * Set a function for dynamically adding elements like a class attribute value specified * - parameters: * Obj target element * Cn class to add value * / Function . AddClass (obj, cn) { // is determined, preventing further execution of the function cn with multiple additions IF (! HasClass (obj, cn)) { obj.className += " "+cn; } } / * Determine whether the element contains a class attribute value specified * If so, returns true * / Function hasClass (obj, CN) { // determines there is no obj cn class, regular expressions var REG = new new the RegExp ( "\\ B" + CN + "\\ B" ); return reg.test(obj.className); } / * Remove a specified element in the class attribute value * / function removeClass (obj, CN) { // create a regular expression var REG = new new the RegExp ( "\\ B" + CN + "\\ B" ); // delete with regular expression matching class obj.className = obj.className.replace (REG, "" ); } / * Switch a class * If there is the class element is deleted; no, add */ function toggleClass(obj,cn){ if(hasClass(obj,cn)){ removeClass(obj,cn); }else{ addClass(obj,cn); } } </script> </html>