js切换不同的div的颜色
四个div,点击一个变色,其他的不变色,效果如图:
代码如下 :
<!DOCTYPE html> <html> <head> <script> window.onload = function(){ var divs = document.getElementsByTagName("div"); var len = divs.length; for(var i=0;i<len;i++){ alert(i); divs[i].onclick = function(){ for(var j=0;j<len;j++){ divs[j].style.backgroundColor = "black"; } this.style.backgroundColor = "red"; }; } }; </script> </head> <body> <div id="div1" style="width:100px;height:100px;background:black;margin:10px;"></div> <div id="div2" style="width:100px;height:100px;background:black;margin:10px;"></div> <div id="div3" style="width:100px;height:100px;background:black;margin:10px;"></div> <div id="div4" style="width:100px;height:100px;background:black;margin:10px;"></div> </body> </html>