Last active
August 29, 2015 14:23
-
-
Save ioslh/67edaf251de4792bac73 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| window.onload=function(){ | |
| //获取页面元素 | |
| var aBtn=document.getElementsByTagName("button"); | |
| var box=document.getElementById("box"); | |
| var tip=document.getElementById("tips"); | |
| //定义三个函数,用三种方式循环改变背景颜色 | |
| var fn=[function(){ | |
| //第一种,遍历取出数组中的颜色值 | |
| var colors=['yellow','red','black','blue','green']; | |
| var i=0; | |
| box.onclick=function(){ | |
| i%=colors.length; | |
| this.style.backgroundColor=colors[i]; | |
| i++; | |
| }; | |
| },function(){ | |
| //第二种 用if else 判断背景颜色并改变 | |
| if(box.style.backgroundColor=="yellow"){ | |
| box.style.backgroundColor="red"; | |
| }else if(box.style.backgroundColor=="red"){ | |
| box.style.backgroundColor="black"; | |
| }else if(box.style.backgroundColor=="black"){ | |
| box.style.backgroundColor="blue"; | |
| }else if(box.style.backgroundColor=="blue"){ | |
| box.style.backgroundColor="green"; | |
| }else{ | |
| box.style.backgroundColor="yellow"; | |
| } | |
| },function(){ | |
| //用switch判断改变背景颜色 | |
| switch(box.style.backgroundColor){ | |
| case "yellow": | |
| box.style.backgroundColor="red"; | |
| break; | |
| case "red": | |
| box.style.backgroundColor="black"; | |
| break; | |
| case "black": | |
| box.style.backgroundColor="blue"; | |
| break; | |
| case "blue": | |
| box.style.backgroundColor="green"; | |
| break; | |
| default: | |
| box.style.backgroundColor="yellow"; | |
| } | |
| }]; | |
| //遍历三个按钮,使用不同的方法来改变背景颜色 | |
| for(var i=0;i<aBtn.length;i++){ | |
| aBtn[i].index=i; | |
| aBtn[i].onclick=function(){ | |
| for(var t=0;t<aBtn.length;t++){ | |
| aBtn[t].className=""; | |
| } | |
| this.className="active"; | |
| box.innerHTML="正在使用"+this.innerHTML+"改变背景颜色"; | |
| box.onclick=fn[this.index]; | |
| }; | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment