简体   繁体   中英

Change animation-duration at any point using JS or jQuery?

I have a simple HTML page with a div in the center of the page and two buttons below it. The animation I want to have is the bg of the div going from black to white in a linear manner in a given duration. This duration would change according to which button I press at the bottom. Changing animation-duration/animationDuration simply with JS doesn't work, this is a known problem as far as I've seen online. I'm open to solutions using jQuery as well.

My code:

 $(".b1").click(function(){ $("#movie").removeClass("t1"); $("#movie").removeClass("t2"); $("#movie").addClass("t1"); }) $(".b2").click(function(){ $("#movie").removeClass("t1"); $("#movie").removeClass("t2"); $("#movie").addClass("t2"); }) 
 body { background: black; margin: 0 auto; max-width: 300px; height: auto; } #movie { width: 300px; height: 200px; background: red; } .t1 { -webkit-animation: change 1s infinite; animation: change 1s infinite; } .t2 { -webkit-animation: change 10s infinite; animation: change 10s infinite; } button { margin-top: 15px; } @keyframes change { from { background-color: black; } to { background-color: white; } } @-webkit-keyframes change { from { background-color: black; } to { background-color: white; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="movie"></div> <button type="button" class="b1">Test 1</button> <button type="button" class="b2">Test 2</button> </body> 

Here is the jsfiddle .

 $(".b1").click(function(){ $("#movie").removeClass("t1"); $("#movie").removeClass("t2"); $("#movie").addClass("t1"); }) $(".b2").click(function(){ $("#movie").removeClass("t1"); $("#movie").removeClass("t2"); $("#movie").addClass("t2"); }) 
 body { background: black; margin: 0 auto; max-width: 300px; height: auto; } #movie { width: 300px; height: 200px; background: red; } .t1 { -webkit-animation: change 1s infinite; animation: change 1s infinite; } .t2 { -webkit-animation: change 10s infinite; animation: change 10s infinite; } button { margin-top: 15px; } @keyframes change { from { background-color: black; } to { background-color: white; } } @-webkit-keyframes change { from { background-color: black; } to { background-color: white; } } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <div id="movie"></div> <button type="button" class="b1">Test 1</button> <button type="button" class="b2">Test 2</button> </body> 

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