2017-07-27 26 views
0

我想要做的就是如果用戶再次按下按鈕,則從頭開始轉換。現在的問題是,如果用戶點擊兩次或更多的按鈕,它不會正確啓動兩個動畫(一個接一個)。Javascript一個接一個地轉換

因此,現在轉換正在工作,但如果用戶多次單擊該按鈕,則無法完成此項工作。

let button = document.querySelector("button") 
let box = document.querySelector(".box") 

button.onclick =() => { 

    box.style.transform = ""; 

    anim1(function(){ 
    anim2(function() { 

    }) 
    }) 

} 


function anim1(cb) { 
    box.style.transition = "" 
    box.clientHeight; 
    box.style.transition = "all 1s"; 
    box.style.transform = "translateX(50px)"; 
    setTimeout(() => { 
    cb() 

    },1000) 
} 

function anim2(cb) { 
    box.style.transition = "" 
    box.clientHeight; 
    box.style.transition = "all 1s"; 
    box.style.transform = "translateX(350px)"; 
    setTimeout(() => { 
    cb() 

    },1000) 
} 

活生生的例子https://jsfiddle.net/kzjpb55f/

回答

1

清除與clearTimeout掛起超時每當你得到一個新的單擊事件:

let button = document.querySelector("button") 
 
let box = document.querySelector(".box") 
 
let timer; // use this variable to trace any pending timeout 
 

 
button.onclick =() => { 
 
    clearTimeout(timer); // clear any pending timeout 
 
    box.style.transform = ""; 
 

 
    anim1(function(){ 
 
    anim2(function() { 
 
     
 
    }) 
 
    }) 
 
    
 
} 
 

 
function anim1(cb) { 
 
    box.style.transition = "" 
 
    box.clientHeight; 
 
    box.style.transition = "all 1s"; 
 
    box.style.transform = "translateX(50px)"; 
 
    timer = setTimeout(cb,1000); // remember last created timeout 
 
} 
 

 
function anim2(cb) { 
 
    box.style.transition = "" 
 
    box.clientHeight; 
 
    box.style.transition = "all 1s"; 
 
    box.style.transform = "translateX(350px)"; 
 
    timer = setTimeout(cb,1000); // remember last created timeout 
 
}
.box { 
 
    height:50px; 
 
    width:50px; 
 
    background-color:red; 
 
}
<button>animate</button> 
 
<div class="box"></div>

0

您可以簡單地添加另一變量,它是真實的,如果有當前的動畫運行,否則爲false。

我與你如何做到這一點的例子。

let button = document.querySelector("button") 
let box = document.querySelector(".box") 
let animating = false; 

button.onclick = (e) => { 



    if (!animating) { 
    box.style.transform = ""; 

    animating = true; 
    anim1(function(){ 
     anim2(function() { 
     animating = false; 
     }) 
    }) 

    } 

} 


function anim1(cb) { 
    box.style.transition = "" 
    box.clientHeight; 
    box.style.transition = "all 1s"; 
    box.style.transform = "translateX(50px)"; 
    setTimeout(() => { 
    cb() 

    },1000) 
} 

function anim2(cb) { 
    box.style.transition = "" 
    box.clientHeight; 
    box.style.transition = "all 1s"; 
    box.style.transform = "translateX(350px)"; 
    setTimeout(() => { 
    cb() 

    },1000) 
} 
相關問題