天天看點

js圖檔輪播效果實作代碼

首先給大家看一看js圖檔輪播效果,如下圖

具體思路:

一、頁面加載、擷取整個容器、所有放數字索引的li及放圖檔清單的ul、定義放定時器的變量、存放目前索引的變量index

二、添加定時器,每隔2秒鐘index遞增一次、調用一次切換圖檔函數

提示:

1、 index不能一直無限制的遞增下去,需做判斷,當大于或者等于目前圖檔數的時候就index歸0,重新開始再次循環

2、調用切換圖檔函數時需将遞增之後的index作為參數傳過去

三、定義圖檔切換函數

提示:

  1.周遊所有放數字索引的li,将每個li上的類去掉。

  2.根據傳遞過來的index值找到對應的li給它添加類設為目前高亮顯示。

  3. 根據傳遞過來的index值計算放圖檔的ul的top值

  4. 改變index的值,讓其等于傳遞過來的參數值

注意:放圖檔的ul的top值=-index*單張圖檔的高度(所有圖檔必須等高)

四、滑鼠劃過整個容器時,圖檔停止切換,離開繼續

提示:

1.  滑鼠滑過整個容器時清除定時器

2.  滑鼠離開時繼續執行定時器,切換至下一張圖檔

五、周遊所有放數字的li,且給他們添加索引、滑鼠滑過時切換至對應的圖檔。

        滑鼠滑過時調用圖檔切換函數,将滑過的li的索引傳過去。

具體代碼如下:

<!doctype html>
<html lang="en">
<head>
 <meta charset="UTF-8">
 <title>Document</title>
 <style>
 *{margin:0;
 padding:0;
 list-style:none;}
 .wrap{height:170px;
 width:490px;
 margin:60px auto;
 overflow: hidden;
 position: relative;
 margin:100px auto;}
 .wrap ul{position:absolute;} 
 .wrap ul li{height:170px;}
 .wrap ol{position:absolute;
 right:5px;
 bottom:10px;}
 .wrap ol li{height:20px; width: 20px;
 background:#ccc;
 border:solid 1px #666;
 margin-left:5px;
 color:#000;
 float:left;
 line-height:center;
 text-align:center;
 cursor:pointer;}
 .wrap ol .on{background:#E97305;
 color:#fff;}
 
 </style>
 <script type="text/javascript">
 window.onload=function(){
 var wrap=document.getElementById(\'wrap\'),
 pic=document.getElementById(\'pic\').getElementsByTagName("li"),
 list=document.getElementById(\'list\').getElementsByTagName(\'li\'),
 index=0,
 timer=null;
 
 // 定義并調用自動播放函數
 timer = setInterval(autoPlay, 2000);
 
 // 滑鼠劃過整個容器時停止自動播放
 wrap.onmouseover = function () {
 clearInterval(timer);
 }
 
 // 滑鼠離開整個容器時繼續播放至下一張
 wrap.onmouseout = function () {
 timer = setInterval(autoPlay, 2000);
 }
 // 周遊所有數字導航實作劃過切換至對應的圖檔
 for (var i = 0; i < list.length; i++) {
 list[i].onmouseover = function () {
 clearInterval(timer);
 index = this.innerText - 1;
 changePic(index);
 };
 };
 
 function autoPlay () {
 if (++index >= pic.length) index = 0;
 changePic(index);
 }
 
 // 定義圖檔切換函數
 function changePic (curIndex) {
 for (var i = 0; i < pic.length; ++i) {
 pic[i].style.display = "none";
 list[i].className = "";
 }
 pic[curIndex].style.display = "block";
 list[curIndex].className = "on";
 }
 
 };
 
 </script> 
</head>
<body>
 <div class="wrap" id=\'wrap\'>
 <ul id="pic">
 <li><img src="1.jpg" alt=""></li>
 <li><img src="2.jpg" alt=""></li>
 <li><img src="3.jpg" alt=""></li>
 <li><img src="4.jpg" alt=""></li>
 <li><img src="5.jpg" alt=""></li> 
 </ul>
 <ol id="list">
 <li class="on">1</li>
 <li>2</li>
 <li>3</li>
 <li>4</li>
 <li>5</li>
 </ol>
 </div>
</body>
</html>