How to activate a CSS3 (webkit) animation using javascript?
Im really stuck. I want a CSS animation I have created (below) to activate on clicking a div. The only way I thought I could do that was using javascript to create an onClick event. However I dont know how to run/refrence the animation that is in my css file. Can anyone help me?
This is the animation in my css file that I want to run by clicking on a div.
@-webkit-keyframes colorchange {
0% {
background-color: red;
opacity: 1.0;
-webkit-transform: scale(1.0) rotate(0deg);
}
33% {
background-color: blue;
opacity: 0.75;
-webkit-transform: scale(1.1) rotate(-5deg);
}
67% {
background-color: green;
opacity: 0.5;
-webkit-transform: scale(1.1) rotate(5deg);
}
100% {
background-color: red;
opacity: 1.0;
-webkit-transform: scale(1.0) rotate(0deg);
}
}
I even tried putting the css in the same file as the javascript (index.html) and used the following code to try and activate it on click, but no luck.
开发者_如何学C<script>
function colorchange( test )
{
test.style.webkitAnimationName = 'colorchange ';
}
</script>
Please help :)
You're missing the duration and you have a trailing space in the name you assign:
function colorchange( test )
{
test.style.webkitAnimationName = 'colorchange'; // you had a trailing space here which does NOT get trimmed
test.style.webkitAnimationDuration = '4s';
}
Some more infos on @-webkit-keyframes
:
http://webkit.org/blog/324/css-animation-2/
update
Some working code.
<html>
<head>
<style>
@-webkit-keyframes colorchange {
0% {
background-color: red;
opacity: 1.0;
-webkit-transform: scale(1.0) rotate(0deg);
}
33% {
background-color: blue;
opacity: 0.75;
-webkit-transform: scale(1.1) rotate(-5deg);
}
67% {
background-color: green;
opacity: 0.5;
-webkit-transform: scale(1.1) rotate(5deg);
}
100% {
background-color: red;
opacity: 1.0;
-webkit-transform: scale(1.0) rotate(0deg);
}
}
</style>
<script>
function colorchange(e) {
if (e.style.webkitAnimationName !== 'colorchange') {
e.style.webkitAnimationName = 'colorchange';
e.style.webkitAnimationDuration = '4s';
// make sure to reset the name after 4 seconds, otherwise another call to colorchange wont have any effect
setTimeout(function() {
e.style.webkitAnimationName = '';
}, 4000);
}
}
</script>
</head>
<body>
<div onclick="colorchange(this)">Hello World!</div>
</body>
</html>
精彩评论