這篇文章主要介紹了js圖片輪播效果實現代碼,文章對每一步進行了詳細闡述,標注注意事項,為順利實現js圖片輪播效果做好鋪墊,對輪播效果感興趣的朋友可以參考一下
首先給大家看一看js圖片輪播效果,如下圖
具體思路:
一、頁面加載、獲取整個容器、所有放數字索引的li及放圖片列表的ul、定義放定時器的變量、存放當前索引的變量index
二、添加定時器,每隔2秒鐘index遞增一次、調用一次切換圖片函數
提示:
1、 index不能一直無限制的遞增下去,需做判斷
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>
以上就是本文的全部內容,為大家分享了js圖片輪播效果實現代碼,希望大家喜歡,根據自己的喜好更換圖片,制作屬于自己的圖片輪播效果。
|
新聞熱點
疑難解答
圖片精選