我真的被困住了。我想要一个我创建的CSS动画(下面)来点击一个div激活。我认为我能做到的唯一方法是使用javascript创建onClick事件。但是我不知道如何运行/参考我的css文件中的动画。任何人都可以帮助我吗?
这是我想通过单击div运行的css文件中的动画。
@-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)相同的文件中,并使用以下代码尝试在点击时激活它,但没有运气。
<script>
function colorchange( test )
{
test.style.webkitAnimationName = 'colorchange ';
}
</script>
请帮助:)
答案 0 :(得分:14)
您错过了持续时间,并且您指定的名称中有一个尾随空格:
function colorchange( test )
{
test.style.webkitAnimationName = 'colorchange'; // you had a trailing space here which does NOT get trimmed
test.style.webkitAnimationDuration = '4s';
}
@-webkit-keyframes
上的更多信息:
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>