巧用数组实现多个内容切换
先看下我开始写的代码吧:
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>切换红绿蓝</title> 6 <style> 7 #div{ 8 width: 100px; 9 height:100px; 10 background-color: red; 11 } 12 </style> 13 </head> 14 <body> 15 <div id="div"></div> 16 <script src="main.js"></script> 17 </body> 18 </html>
1 /** 2 * Created by Administrator on 2016/8/8. 3 */ 4 (function () { 5 6 var div = document.getElementById("div"); 7 var i = 1; 8 9 function backgroundColor(color) { 10 var e=div.style.backgroundColor=color; 11 return e; 12 } 13 function ClickToSwitchColor() { 14 if (i % 3 == 0) { 15 backgroundColor("red"); 16 // div.style.backgroundColor = "red"; 17 } else if (i % 2 == 0) { 18 backgroundColor("blue"); 19 // div.style.backgroundColor = "blue"; 20 } else { 21 backgroundColor("green"); 22 // div.style.backgroundColor = "green"; 23 } 24 i++; 25 } 26 27 div.addEventListener("click", ClickToSwitchColor); 28 29 }) 30 ();
我的代码可以实现,但是没有良好的扩展性,如再添加一中颜色遍不容易。
看下优化的代码吧
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>d</title> 6 <style> 7 #div{ 8 width: 100px; 9 height:100px; 10 background-color: red; 11 } 12 </style> 13 </head> 14 <body> 15 <div id="div"></div> 16 <script src="main01.js"></script> 17 </body> 18 </html>
1 /** 2 * Created by Administrator on 2016/8/8. 3 */ 4 (function () { 5 var colors=["red","blue","pink","yellow","green"]; 6 var div=document.getElementById("div"); 7 var index=0; 8 div.addEventListener("click",function (event) { 9 index++; 10 if(index>=colors.length){ 11 index=0; 12 } 13 div.style.backgroundColor=colors[index]; 14 }); 15 })();
如代码,巧用数组,实现颜色切换。
应用这个原理也可以实现图片切换,无非在数组里面放上路径而已。
看下代码吧
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 8 9 </style> 10 </head> 11 <body> 12 <div id="div"> 13 <img src="1.jpg" id="img1"/> 14 </div> 15 16 17 <script src="main.js"></script> 18 </body> 19 </html>
1 /** 2 * Created by Administrator on 2016/8/8. 3 */ 4 (function () { 5 var img = document.getElementById("img1"); 6 var images = ["1.jpg", "2.jpg", "3.jpg"]; 7 var index = 0; 8 setInterval(function () { 9 index++; 10 if (index >= images.length) { 11 index = 0; 12 } 13 img.src = images[index]; 14 }, 3000); 15 })();
myGitgub https://github.com/mfx55
希望我的博客能帮到你