1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 5 <title>2016011220160115</title> 6 7 <style> 8 #set_color{ 9 display: inline-block; 10 width: 80px; 11 text-align: center; 12 background-color: red; 13 font-size: 16px; 14 padding: 10px 0; 15 color:white; 16 cursor: pointer; 17 } 18 #layer{ 19 display: none; 20 } 21 22 #layer_bg{ 23 background-color: black; 24 opacity: 0.2; 25 top:0; 26 left:0; 27 width: 100%; 28 height:100%; 29 position: fixed; 30 z-index: 10; 31 } 32 #layer_content{ 33 width: 15%; 34 margin-left: 40%; 35 background-color: white; 36 opacity: 1; 37 padding: 20px; 38 z-index: 20; 39 position: absolute; 40 } 41 #target_div{ 42 border: 5px solid #000; 43 width: 100px; 44 height:100px; 45 } 46 </style> 47 </head> 48 49 <body> 50 <p><strong>请为下面的DIV设置样式:</strong><span id="set_color">点击设置</span></p> 51 <div id="target_div"> 52 </div> 53 <div id="layer"> 54 <div id="layer_bg"> 55 </div> 56 <div id="layer_content"> 57 <p> 58 <span>请选择背景色:</span> 59 <button value="红">红</button> 60 <button value="黄">黄</button> 61 <button value="蓝">蓝</button> 62 </p> 63 <p> 64 请选择宽(PX): 65 <button value="200">200</button> 66 <button value="300">300</button> 67 <button value="400">400</button> 68 </p> 69 <p> 70 请选择高(PX): 71 <button value="200">200</button> 72 <button value="300">300</button> 73 <button value="400">400</button> 74 </p> 75 <button value="恢复">恢复</button> 76 <button value="确定">确定</button> 77 </div> 78 </div> 79 80 81 <script type="text/javascript"> 82 var btns = document.getElementsByTagName(‘button‘); 83 var tarDiv = document.getElementById(‘target_div‘); 84 var colors = [‘red‘,‘yellow‘,‘blue‘,‘200px‘,‘300px‘,‘400px‘]; 85 for (var i = 0; i < btns.length - 1; i++) { 86 btns[i].onclick = function(i){ 87 /********闭包的样例,破解闭包***********/ 88 return function(){ 89 if(i>=0 && i<=2){ 90 tarDiv.style.background = colors[i]; 91 } 92 else if(i>=3 && i<=5){ 93 tarDiv.style.width = colors[i]; 94 } 95 else if(i>=6 && i<=8){ 96 tarDiv.style.height = colors[i-3]; 97 } 98 }; 99 }(i); 100 }; 101 102 btns[9].onclick = function(){ 103 tarDiv.style.background = ‘white‘; 104 tarDiv.style.width = ‘100px‘; 105 tarDiv.style.height = ‘100px‘; 106 } 107 108 btns[3].onmouseover = function(){ 109 tarDiv.style.background = ‘#CC6666‘; 110 tarDiv.style.width = ‘200px‘; 111 } 112 btns[10].onclick = function(){ 113 document.getElementById(‘layer‘).style.display = ‘none‘; 114 } 115 document.getElementById(‘set_color‘).onclick = function(){ 116 document.getElementById(‘layer‘).style.display = ‘block‘; 117 }; 118 119 </script> 120 </body> 121 </html>
原文:http://www.cnblogs.com/xiayedexin/p/5133256.html