1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Document</title> 6 <script type="text/javascript" src="../jquery-1.12.4.min.js"></script> 7 <script type="text/javascript"> 8 $(function(){ 9 var $btn = $('#btn'); 10 var $div1 = $('#div1'); 11 // 绑定click事件 12 $btn.click(function(){ 13 if($div1.hasClass('changecolor')) 14 { 15 $div1.removeClass('changecolor'); 16 } 17 else 18 { 19 $div1.addClass('changecolor'); 20 } 21 }); 22 // $btn.hasClass('changecolor');判断是否有changecolor这样式,有返回true 23 }); 24 25 </script> 26 27 <style type="text/css"> 28 div{ 29 width: 300px; 30 height: 300px; 31 line-height: 300px; 32 margin: 50px auto 0; 33 text-align: center; 34 } 35 .box{ 36 background-color: gold; 37 } 38 .changecolor{ 39 background-color: green; 40 } 41 </style> 42 </head> 43 <body> 44 <input type="button" name="" value="切换样式" id="btn"> 45 <div class="box" id="div1">这是div元素</div> 46 </body> 47 </html>