1. 程式人生 > >javascript輪播圖效果

javascript輪播圖效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>javascript焦點圖</title>
    <style>
        *{margin:0;padding:0;}
        li{list-style: none;}
        #container{position:relative;width:680px;height:344px;overflow:hidden;margin:50px auto
;font-size:13px;} #container img{width:680px;height:344px;} #tabs li{width:20px;height:20px;background:#000;color:#fff;float:left;margin-right:5px;text-align:center;line-height:20px;cursor: pointer;} #tabs{position:absolute;right: 10px;bottom:10px;} #tabs .active{background:#d75509
;} #arrow{left:5px;bottom:5px;position:absolute;} #arrow span{width: 20px;height: 20px;display: inline-block;background: #000;color: #fff;text-align: center;cursor:pointer;} #content div{width: 680px;height: 344px;display:none;} #content .active{display:block;} #container ul li.active
{background:yellow;} </style> </head> <body> <div id="container"> <ul id="tabs"> <li data-index ="0" class="active">1</li> <li data-index ="1">2</li> <li data-index ="2">3</li> <li data-index ="3">4</li> </ul> <div id="content"> <div class="active"><img src="images/1.jpg" alt=""></div> <div><img src="images/2.jpg" alt=""></div> <div><img src="images/3.jpg" alt=""></div> <div><img src="images/4.jpg" alt=""></div> </div> <div id="arrow"> <span>&lt;</span> <span>&gt;</span> </div> </div> <script>
var aLi = document.querySelectorAll('#tabs li');//arr,圖索引 var oContainer = document.querySelector('#container'); var aDiv = document.querySelectorAll('#content div'); var aSpan = document.querySelectorAll('#arrow span'); var index=0;//上下圖 var timer=null; for(var i=0;i<aLi.length;i++){ //迴圈時就存索引,js中沒有屬性index,自定義的 aLi[i].index = i; //進入onclick前for已經迴圈到4 aLi[i].onclick=function(){ index=this.index; switchImg(this.index); } } //圖片切換函式 function switchImg(idx){ //去掉所有高亮 for(var j=0;j<aLi.length;j++){ aLi[j].className=''; aDiv[j].className=''; } //this.index =this.getAttribute('data-index')//或在html中加入自定義索引data-index屬性 aLi[idx].className='active'; aDiv[idx].className='active'; } //切換右測圖片< aSpan[0].onclick=function(){ index--; if(index<0){ index=aLi.length-1; } switchImg(index); } //> aSpan[1].onclick=function(){ index++; if(index==aLi.length){ index=0; } switchImg(index); } //自動播放,呼叫點選>事件 timer = setInterval(function(){ aSpan[1].onclick(); },1000) oContainer.onmouseover = function(){ clearInterval(timer); timer =null; } oContainer.onmouseout = function(){ timer = setInterval(function(){ aSpan[1].onclick(); },1000) } </script> </body> </html>