一个简单幻灯片

初学JS,会尝试去做一些实例。现将做过的一些放上来,记录自己的学习过程。

此实例没有动画效果,只是简单的变化。但是基本功能已经达到了。

这是第一次真正运用到三元运算符,还用利用闭包传递索引值。

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>slide</title>
 6 <style type="text/css">
 7 body { background:#000; font-size:12px; }
 8 ul { list-style:none; }
 9 #slideBox { width:704px; height:356px; border:#fff solid 5px; margin:50px auto; overflow:hidden; position:relative; }
10 #slideBox ul { position:absolute; z-index:999; right:5px; bottom:0px; }
11 #slideBox li { float:left; width:18px; height:18px; margin-right:8px; line-height:18px; background:#fff; text-align:center; border:#ddd solid 1px; cursor:pointer; }
12 #slideBox li.cur { background:#d59; color:#fff; font-weight:bold; }
13 </style>
14 </head>
15 <body>
16     <div id="slideBox">
17         <img src="images/slide03.jpg" alt="" />
18         <img src="images/slide02.jpg" alt="" />
19         <img src="images/slide01.jpg" alt="" />
20         <ul>
21             <li class="cur">1</li>
22             <li>2</li>
23             <li>3</li>
24         </ul>
25     </div>
26     <script type="text/javascript">
27     var oImg = document.getElementById("slideBox").getElementsByTagName("img");
28     var oLi = document.getElementById("slideBox").getElementsByTagName("li");
29     var n = 0;
30     for(var i=0; i<oImg.length; i++) {
31         oImg[i].onmouseover = function() {
32             clearTimeout(stopPlay);
33         }
34         oImg[i].onmouseout = function() {
35             n=n===0?2:n-1;   //为了在鼠标离开时不立即跳到下一张
36             autoPlay();
37         }
38     }
39     for(var i=0; i<oLi.length; i++) {
40         //应用js闭包传入参数i作为当前索引值赋值给m
41         (function(m) {
42             oLi[m].onmouseover = function() {
43                 clearTimeout(stopPlay);
44                 for(var j=0; j<oLi.length; j++) {
45                     oLi[j].className = "";
46                     oImg[j].style.display = "none";
47                 }
48                 this.className = "cur";
49                 oImg[m].style.display = "block";
50             }
51             
52             oLi[m].onmouseout = function() {
53                 n = m;
54                 autoPlay();
55             }
56         })(i);
57     }
58     
59     function autoPlay() {
60         for(var i=0; i<oImg.length; i++) {
61             oImg[i].style.display = "none";
62             oLi[i].className = "";
63         }
64         oImg[n].style.display = "block";
65         oLi[n].className = "cur";
66         n=n===2?0:n+1;
67         stopPlay = setTimeout(autoPlay,2000);
68     }
69     autoPlay();
70     
71     </script>
72 </body>
73 </html>
posted @ 2012-05-04 10:21  长风freedom  阅读(130)  评论(0编辑  收藏  举报