简体   繁体   English

使用Javascript生成随机Webkit动画

[英]Generate Random Webkit Animation with Javascript

I was wondering if it is possible to generate a webkit animation with javascript. 我想知道是否有可能用javascript生成webkit动画。 Basically all I need is that if i click element A, element B should be animated with a random parameter every time(this is why I cant use a pre-fixed CSS). 基本上,我需要的是,如果我单击元素A,则元素B每次都应使用随机参数设置动画(这就是为什么我不能使用预先固定的CSS的原因)。 I'm testing if I can actually generate all this through javascript and Ive gotten pretty far. 我正在测试我是否真的可以通过javascript生成所有这些内容,而我已经走得很远了。 My code does not do anything random yet but it is really easy to make it random once I get it to work right with javasript. 我的代码还没有做任何随机的事情,但是一旦我使它可以正确地与javasript一起使用,就可以很容易地使其随机。 So right now I just want to animate element B every time I click element A. My code looks like this: 因此,现在我只想在每次单击元素A时为元素B设置动画。我的代码如下所示:

$("#elementA").live('touchstart mousedown',function() {

$("head style").remove();
var cssAnimation  = document.createElement('style');
cssAnimation.type = 'text/css';
var rules = document.createTextNode('@-webkit-keyframes random_spin {'+
'from   { -webkit-transform: rotate(0deg);      }'+
'to     { -webkit-transform: rotate(1440deg);   }'+
'}');

cssAnimation.appendChild(rules);
document.getElementsByTagName("head")[0].appendChild(cssAnimation);

$("#elementB").removeClass("random_spin");
$("#elementB").css({'-webkit-animation-name': ''});

$("#elementB").css({'-webkit-animation-name': 'random_spin'});
$("#elementB").addClass("random_spin");
});

There I just added the animation to the header and I applied it to elementB. 在那里,我只是将动画添加到标题中,并将其应用于elementB。

My "random_spin" class is a CSS I already predefined : 我的“ random_spin”类是我已经预定义的CSS:

.random_spin {
    -webkit-animation-duration:         5s;  
    -webkit-animation-timing-function:  ease;
}

My intention with this is that I should be able to make my elementB spin every time I click on elementA. 我的意图是,每次单击elementA时,都应该能够使elementB旋转。 Unfortunately it only does it once and no matter how much I click on it or how many times I reset the animation name it still only does it once. 不幸的是,它只执行一次,无论单击多少次或重置动画名称多少次,它仍然只执行一次。 What am I doing wrong? 我究竟做错了什么?

To restart a CSS3 animation you cannot just remove and add a class without putting a small delay between the commands. 要重新启动CSS3动画,您不能只删除并添加类而不在命令之间稍加延迟。 This allows the browsers time to actually remove the class before adding the new one. 这使浏览器有时间在添加新类之前实际删除该类。 You can do this with a simple setTimeout 您可以使用简单的setTimeout来完成此操作

setTimeout(function(){
    $("#elementB").addClass("random_spin");
}, 100);

More information and examples can be found below. 可以在下面找到更多信息和示例。

http://css-tricks.com/restart-css-animation/ http://css-tricks.com/restart-css-animation/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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