简体   繁体   中英

How to increase Animation Duration on every click in JS?

CSS

#plus{ animation-duration: 5s;}

I want to increase it on every click using JavaScript...

JS Code

var increasePlus = document.getElementById("plus");  
increasePlus.addEventListener('click', () => {
var sec= 5 + "s";    
if(sec=="5s"){
   sec = 6 + "s";
   increasePlus.style.animationDuration = sec;
}   
if(sec=="6s"){
   sec = 7 + "s";
   increasePlus.style.animationDuration = sec;
}   
});

It doesn't work !!!

Going through the logic of the given code we can see that the animation-duration is always set to the same amount (7s) on every click - it never changes after the first click:

var increasePlus = document.getElementById("plus");  
increasePlus.addEventListener('click', () => {
var sec= 5 + "s";    
if(sec=="5s"){//this is always true as sec has just been set to 5s
   sec = 6 + "s";//so sec is set to 6s
   increasePlus.style.animationDuration = sec;
}   
if(sec=="6s"){//this is always true as sec has (just) been set to 6s
   sec = 7 + "s";//so sec is now set to 7s
   increasePlus.style.animationDuration = sec;//and so the animation-duration is ALWAYS set to 7s on a click
}   
});

It is difficult to click on a moving object which is what the given code seems to require (the clickable element id plus is also the one given the animation duration in that code) so in this snippet the plus element gets clicked and that updates the animation duration of a separate object which is the one that moves.

 const increasePlus = document.getElementById("plus"); const theObject = document.getElementById('object'); increasePlus.addEventListener('click', () => { //get the current animation-duration //remember this has an s at the end so we need to get rid of that so we can add to it let sec= window.getComputedStyle(theObject, null)["animationDuration"].replace('s',''); //add 1 to it sec++; //and set the animation-duration theObject.style.animationDuration = sec + 's'; });
 #plus{ font-size: 60px; } #object { position: relative; animation-name: move; animation-duration: 5s; animation-iteration-count: infinite; animation-timing-function: linear; width: 100px; height: 100px; background-color: magenta; } @keyframes move { 0% { top: 0; } 100% { top: 30vh; } }
 <button id="plus">+</button> <div id="object"></div>

I think this can fail because of this line

var sec= 5 + "s";  

this line will execute always when you click on the button, so after that in "if" condition you will always get sec = '5s' and than it will be decreased to '4s'.

If you want that code to work, you could place "var sec = 5+'s' above the listener declaration.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM