如何使用javascript激活CSS3(webkit)动画? [英] How to activate a CSS3 (webkit) animation using javascript?
问题描述
我真的卡住了。我想要一个CSS动画我创建(下面)激活单击一个div。我唯一的方法,我想我可以做的是使用javascript来创建一个onClick事件。但我不知道如何运行/ refrence在我的css文件中的动画。任何人都可以帮助我?
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?
这是我的css文件中的动画,我想通过点击div运行。
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);
}
}
我甚至尝试将css放在同一个文件javascript(index.html)并使用以下代码尝试在点击时激活它,但没有运气。
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.
<script>
function colorchange( test )
{
test.style.webkitAnimationName = 'colorchange ';
}
</script>
请帮助:)
推荐答案
您缺少持续时间,并且您分配的名称中有一个结尾空格:
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';
}
/ code>:
http://webkit.org/blog/324 / css-animation-2 /
更新
工作代码。
<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>
这篇关于如何使用javascript激活CSS3(webkit)动画?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!