JS的setInterval定時器


之前的博文:JS點擊上一張下一張輪播li標簽1
是通過點擊按鈕切換上一張下一張圖片,這個是手動操作的,JS里還有定時器可以設置每隔多少時間執行一次。
例如之前博文的那個,把下一張的next()方法,掛到定時器上,每隔一秒執行一次這個next()方法,就可以實現每隔一秒自動切換圖片。
格式:setInterval(方法,時間);
例如 :setInterval(next(),1000);//每隔一秒執行一次next()方法。
這里的1000單位是毫秒,秒和毫秒的換算單位為:1秒=1000毫秒

測試代碼:這里用log輸出下時間,測試下每次執行的方法的時間。定時器前面的代碼都是之前博文的,有介紹。

<style>
.box1{list-style-type:none;width:200px;height:100px;overflow:hidden;position:relative;}
.box1 li{width:200px;height:100px;position:absolute;top:0px;left:0px;}
.box1 li.now{opacity:1;}/**1代表完全不透明**/
.box1 li.others{opacity:0;}/**1代表完全透明**/
 </style>
 </head>
 <body>
 <div class="box1">
     <ul class="list1">
       <li id="img1" class="now"><img src="images/img1.png"></li>
       <li id="img2" class="others"><img src="images/img2.png"></li>
       <li id="img2" class="others" style="background:red"></li>
     </ul>
 </div>
 <input type="button" value="上一張" onclick="pre()"><br>
  <input type="button" value="下一張" onclick="next()">
 <script>
 var index=0;
 var lis=document.getElementsByTagName("li");
 var indexlength=lis.length-1;//長度-1是最后一個的索引
function pre(){
    index--;
    if(index<0)
    {
        index=indexlength;
    }  
    for(var i=0;i<lis.length;i++)
    {
     lis[i].className="others";
    }
    lis[index].className="now";
};
function next(){
    index++;
    if(index>indexlength)
    {
        index=0;
    }  
    for(var i=0;i<lis.length;i++)
    {
     lis[i].className="others";
    }
    lis[index].className="now";
};
var timer=setInterval(function(){next();var date=new Date();console.log("時間:"+(new Date()).toLocaleTimeString());},1000);
 </script>

圖示 :
共3張圖片,循環播放這三個圖,由於index索引是從0開始的,所以第0張就是第一張,第1張就是第2張,第2張就是第三張。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM