js更改图片透明度实现轮播图轮播效果
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <title>Title</title> 6 <style> 7 html body { 8 margin: 0; 9 padding: 0; 10 } 11 li{ 12 list-style: none; 13 } 14 .div1{ 15 width: 500px; 16 height: 400px; 17 margin: 50px auto; 18 position: relative; 19 border: 1px solid black; 20 21 } 22 .div1 a img { 23 width: 400px; 24 position: absolute; 25 margin: 118px 50px; 26 } 27 .div1 ul{ 28 position: absolute; 29 bottom: 110px; 30 right:53px; 31 z-index: 10; 32 } 33 .div1 ul li { 34 width: 15px; 35 height: 15px; 36 line-height: 15px; 37 border-radius: 50%; 38 float: left; 39 background-color: white; 40 margin-right: 5px; 41 cursor: pointer; 42 text-align: center; 43 } 44 </style> 45 </head> 46 <body> 47 <div class="div1" id="div1"> 48 <a href="javascript:void(0)"><img src="img/1.png"></a> 49 <a href="javascript:void(0)"><img src="img/2.png"></a> 50 <a href="javascript:void(0)"><img src="img/3.png"></a> 51 <a href="javascript:void(0)"><img src="img/44.jpg"></a> 52 <a href="javascript:void(0)"><img src="img/55.jpg"></a> 53 <ul> 54 <li>1</li> 55 <li>2</li> 56 <li>3</li> 57 <li>4</li> 58 <li>5</li> 59 </ul> 60 </div> 61 <script> 62 var div1 = document.getElementById("div1");//整个区域 63 var a1 = div1.getElementsByTagName("a");//a标签 图片 64 var li1 = div1.getElementsByTagName("li");//右下角按钮 65 var ab = 0; //ab的值控制触摸按钮后的下一张图 66 //遍历所有图和按钮,页面加载完毕显示第一张图和第一个按钮 67 window.onload = function () { 68 for (var i=0;i<a1.length;i++){ 69 if (i!=0){ 70 a1[i].style.opacity = 0; 71 }else { 72 li1[i].style.backgroundColor = "green"; 73 } 74 } 75 }; 76 //运行函数bb(); 77 function bb() { 78 for (var j=0;j<li1.length;j++) { 79 //遍历所有的按钮,所有按钮都给绑定一个鼠标移上去的onmouseover事件 80 li1[j].onmouseover = function () { 81 //变量index就是当前触摸的按钮的文本-1,此前特意设置按钮文本为数字 82 var index = this.innerHTML - 1; 83 ab = index; //ab后面用return返回 84 //声明变量b 85 for (var b = 0; b < li1.length; b++) { 86 //当b就是被触摸到的按钮的索引号时,设置第b张图片不透明度为100,渐变透明度效果1s,第b个按钮背景色变成green 87 if (b == index) { 88 a1[b].style.opacity = 100; 89 a1[b].style.transition = "opacity 1s"; 90 li1[b].style.backgroundColor = "green"; 91 } else { //当b不是被触摸到的按钮的索引号时,就变透明,按钮颜色白色. 92 a1[b].style.opacity = 0; 93 li1[b].style.backgroundColor = "white"; 94 } 95 } 96 return ab; //返回ab,貌似运用到了闭包?不太了解. 97 } 98 99 } 100 setInterval(function ac() { //设置2000毫秒重复运行 101 ab = ab>li1.length-2?0:++ab; //5张图,当触摸到的按钮索引号大于3时(比如4),那么ab=0(下一张图为第0张),否则++ab; 102 //循环遍历下一张图的效果. 103 for (var b = 0; b < li1.length; b++) { 104 if (b == ab) { 105 a1[b].style.opacity = 100; 106 a1[b].style.transition = "opacity 1s"; 107 li1[b].style.backgroundColor = "green"; 108 } else { 109 a1[b].style.opacity = 0; 110 li1[b].style.backgroundColor = "white"; 111 } 112 } 113 },2000); 114 } 115 bb(); //运行bb() 116 </script> 117 </body> 118 </html>
貌似用到了闭包?菜鸟新手不是很理解.
参考:阮一峰的网络日志
http://www.ruanyifeng.com/blog/2009/08/learning_javascript_closures.html