這篇文章主要介紹了js圖片輪播效果實(shí)現(xiàn)代碼,文章對每一步進(jìn)行了詳細(xì)闡述,標(biāo)注注意事項(xiàng),為順利實(shí)現(xiàn)js圖片輪播效果做好鋪墊,對輪播效果感興趣的朋友可以參考一下
首先給大家看一看js圖片輪播效果,如下圖
具體思路:
一、頁面加載、獲取整個容器、所有放數(shù)字索引的li及放圖片列表的ul、定義放定時器的變量、存放當(dāng)前索引的變量index
二、添加定時器,每隔2秒鐘index遞增一次、調(diào)用一次切換圖片函數(shù)
提示:
1、 index不能一直無限制的遞增下去,需做判斷
2、調(diào)用切換圖片函數(shù)時需將遞增之后的index作為參數(shù)傳過去
三、定義圖片切換函數(shù)
提示:
1.遍歷所有放數(shù)字索引的li,將每個li上的類去掉。
2.根據(jù)傳遞過來的index值找到對應(yīng)的li給它添加類設(shè)為當(dāng)前高亮顯示。
3. 根據(jù)傳遞過來的index值計(jì)算放圖片的ul的top值
4. 改變index的值,讓其等于傳遞過來的參數(shù)值
注意:放圖片的ul的top值=-index*單張圖片的高度(所有圖片必須等高)
四、鼠標(biāo)劃過整個容器時,圖片停止切換,離開繼續(xù)
提示:
1. 鼠標(biāo)滑過整個容器時清除定時器
2. 鼠標(biāo)離開時繼續(xù)執(zhí)行定時器,切換至下一張圖片
五、遍歷所有放數(shù)字的li,且給他們添加索引、鼠標(biāo)滑過時切換至對應(yīng)的圖片。
鼠標(biāo)滑過時調(diào)用圖片切換函數(shù),將滑過的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;
- // 定義并調(diào)用自動播放函數(shù)
- timer = setInterval(autoPlay, 2000);
- // 鼠標(biāo)劃過整個容器時停止自動播放
- wrap.onmouseover = function () {
- clearInterval(timer);
- }
- // 鼠標(biāo)離開整個容器時繼續(xù)播放至下一張
- wrap.onmouseout = function () {
- timer = setInterval(autoPlay, 2000);
- }
- // 遍歷所有數(shù)字導(dǎo)航實(shí)現(xiàn)劃過切換至對應(yīng)的圖片
- 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);
- }
- // 定義圖片切換函數(shù)
- 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>
以上就是本文的全部內(nèi)容,為大家分享了js圖片輪播效果實(shí)現(xiàn)代碼,希望大家喜歡,根據(jù)自己的喜好更換圖片,制作屬于自己的圖片輪播效果。
新聞熱點(diǎn)
疑難解答
圖片精選