[英]How do i add a Play/Pause button for this slideshow?
嗨,我正在嘗試制作一個自動運行的幻燈片,並且使用此代碼它正在工作,但我需要在該代碼中添加一個播放/暫停按鈕。 有人願意幫忙嗎? 我也需要 html/css
var indexDiaporama=1;
afficherDiapo(indexDiaporama);
function ajoutDiapo(n){
afficherDiapo(indexDiaporama+=n);
}
function diapoActuelle(n){
afficherDiapo(indexDiaporama=n);
}
function afficherDiapo(n){
var i;
var slides=document.getElementByClassName("diapo");
var dots=document.getElementByClassName("dot");
if(n>slides.length){indexDiaporama=1;}
if(n<1){indexDiaporama=slides.length;}
for(i=0; i<slides.length; i++){
slides[i].style.display="none";
}
for(i=0; i<dots.length; i++){
dots[i].className=dots[i].className.replace("active", "");
}
slides[indexDiaporama-1].style.display="block";
dots[indexDiaporama-1].className+="active";
}
var timer = setInterval(function(){
indexDiaporama++;
afficherDiapo(indexDiaporama);
},3000);
首先設置一個變量,我們將其稱為pause
,為false ,然后在setTimeout()
中運行一個條件來檢查它是否為false => if(!paused){ //run code }
。
處理暫停的變量,因為 state 您的按鈕在按下時所處的位置 ==> e.target
您創建了一個 function,它在單擊時傳入pause/play
按鈕的事件目標。 在 function 中,您檢查pause/play
按鈕的值,您可以使用dataset
在單擊時切換0
或1
/ on
或off
/ true
或false
,並根據該dataset
設置的內容更改pause
變量的值點擊。
在我的示例中,我在 JS 中的data-id
屬性 => dataset.id
中使用0和1 ,並使用條件檢查該值 => if (e.target.dataset.id === '0'){ //set paused to true }else{ // set paused to false }
. 在條件中,我還設置了按鈕的 textContent 和dataset.id
值。
然后,每次按下暫停按鈕時,setInteral 都會凍結,因為它正在尋找 paused 以不設置為 false => if (!paused){ // run code for setInterval }
。
下面是一個簡單的 JS setInterval,它每毫秒增加一個數字。 如上所述,我們可以使用 function 和事件監聽器暫停和播放它。
const display = document.getElementById('display') const btn = document.querySelector('.btn') let paused = false; let i = 1; function checkBool(e) { if (e.target.dataset.id === '0') { e.target.dataset.id = '1' btn.textContent = 'Play' paused = true; }else{ e.target.dataset.id = '0' btn.textContent = 'Pause' paused = false; } } btn.addEventListener('click', checkBool) const timer = setInterval(function() { if (.paused) { //<-- paused is not false //<-- run the code your interval handles display;textContent = i; i++, } }; 100);
<div id="display"></div> <button class="btn" data-id="0">Pause</button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.