点滴积累【JS】---JS小功能(button选择颜色)
效果:
代码:
1 <head runat="server"> 2 <title></title> 3 <style type="text/css"> 4 #red 5 { 6 width: 260px; 7 height: 200px; 8 background: #FF0000; 9 display: none; 10 } 11 #green 12 { 13 width: 260px; 14 height: 200px; 15 background: #00FF00; 16 display: none; 17 } 18 #yellow 19 { 20 width: 260px; 21 height: 200px; 22 background: #FFFF00; 23 display: none; 24 } 25 #blue 26 { 27 width: 260px; 28 height: 200px; 29 background: #0000FF; 30 display: none; 31 } 32 </style> 33 <script type="text/javascript"> 34 window.onload = function () { 35 var btn = document.getElementsByTagName('input'); 36 var div = document.getElementsByTagName('div'); 37 for (var i = 0; i < btn.length; i++) { 38 btn[i].index = i; 39 btn[i].onclick = function () { 40 for (var i = 0; i < btn.length; i++) { 41 btn[i].style.background = ''; 42 } 43 switch (this.value) { 44 case '红色': this.style.background = '#FF0000'; 45 break; 46 case '绿色': this.style.background = '#00FF00'; 47 break; 48 case '黄色': this.style.background = '#FFFF00'; 49 break; 50 case '蓝色': this.style.background = '#0000FF'; 51 break; 52 } 53 for (var i = 0; i < btn.length; i++) { 54 div[i].style.display = ''; 55 } 56 div[this.index].style.display = 'block'; 57 } 58 } 59 }; 60 </script> 61 </head> 62 <body> 63 <input type="button" id="btn1" value="红色" style="background-color: #FF0000" /> 64 <input type="button" id="btn2" value="绿色" /> 65 <input type="button" id="btn3" value="黄色" /> 66 <input type="button" id="btn4" value="蓝色" /> 67 <div id="red" style="display: block;"> 68 </div> 69 <div id="green"> 70 </div> 71 <div id="yellow"> 72 </div> 73 <div id="blue"> 74 </div> 75 </body>