1. 程式人生 > >JS圖片輪播

JS圖片輪播

其余 次循環 none cit cnblogs 屬性 變色 float pic

輪播就是一組圖,每次顯示一張
1. 先定義兩個函數:顯示某圖,隱藏某圖
2. 寫自動輪播
3. 寫點擊按鈕的圖片切換

技術分享

<!DOCTYPE html>
<html>

    <head>
        <meta charset="UTF-8">
        <title>Carousel·輪播</title>
        <style>
            div.outer {
                width: 200px;
                height
: 200px; border: 1px solid #CCC; /*留點邊界,美觀*/ padding: 5px; } div.per { /*充滿父div*/ width: 100%; height: 100%; /*border: 1px solid #CCC;這個留著的話,ahShadow層有一個px的誤差對不齊
*/ /*默認不顯示*/ display: none; } .per .pic { height: 100%; width: 100%; } .per .title { color: blue; font-family: "微軟雅黑"; /*
位置調整*/ position: relative; bottom: 25px; left: 5px; } div.ahShadow { height: 20px; width: 100%; background-color: #666; /*位置調整*/ position: relative; bottom: 20px; /*透明度*/ opacity: 0.5; /*透明度——IE不支持opacity*/ filter: alpha(opacity=50); } /*↓↓↓按鈕*/ .divBtns { position: relative; bottom: 40px; right: 5px; /*右置*/ float: right; } .divBtns a { width: 20px; height: 20px; background-color: #50F0D8; /*文字處理*/ text-align: center; text-decoration: none; /*行內塊顯示*/ display: inline-block; } </style> </head> <body> <div class="outer"> <div class="per"> <img class="pic" src="img/sh1.png" /> <div class="title">圖片1</div> </div> <div class="per"> <img class="pic" src="img/sh2.png" /> <div class="title">圖片2</div> </div> <!---------------------------------------> <div class="ahShadow"></div> <!---------------------------------------> <div class="divBtns" id="btn-ahref"> <!--加一張圖,就需要加一個按鈕--> <a href="javascript:void(0)" class="abtn">1</a> <a href="javascript:void(0)" class="abtn">2</a> </div> </div> <script> var divlist = document.getElementsByClassName("per"); var btns = document.getElementsByClassName("abtn"); function picShow(idx) { // 圖片顯示 divlist[idx].style.display = "block"; // 按鈕變色 btns[idx].style.backgroundColor = "#FFF"; } function picHiden(idx) { divlist[idx].style.display = "none"; btns[idx].style.backgroundColor = "#50F0D8"; } //自動輪播 function autoShow() { for (var i = 0; i < divlist.length; i++) { if (divlist[i].style.display == "block") { // 讓顯示的圖片不顯示 picHiden(i); // 下一張顯示 if (i == divlist.length - 1) { picShow(0); } else { picShow(i + 1); } // 做完了就撤 break; } } } // 初始化 picShow(0); // 定時輪播 setInterval("autoShow()", 5000); </script> <script> // 手動輪播 debugger; for (i = 0; i < btns.length; i++) { //i是不停在變的,每次循環要把i的當前值固定下來 // 自定義一個屬性“idx”來存放i的值 btns[i].idx = i; btns[i].onclick = function() { // 當前下標對應的圖片可見,其余圖片不可見 for (j = 0; j < divlist.length; j++) { picHiden(j); } picShow(this.idx); } } </script> </body> </html>

JS圖片輪播