如何使用字符串中的变量更改CSS属性

时间:2015-08-01 11:00:27

标签: javascript jquery css html5

所以我试图改变页面上某些东西的速度动画,但是当我尝试在字符串部分中使用变量名时,动画会中断。我确定这只与我如何处理字符串有关,但我已经尝试了几种替代方案,我的动画仍然会中断。如果以某种方式告诉我,我会很感激。

var speed = 5;
speed = speed.toString() + 's infinite';

$('#ball').click(function () {
    $('#ball').css('animation', 'bounce' + speed);
});

2 个答案:

答案 0 :(得分:0)

底部功能包括动画;

animation-name: initial;
animation-duration: 3s;
animation-timing-function: bounce;
animation-delay: initial;
animation-iteration-count: infinite;
animation-direction: initial;
animation-fill-mode: initial;
animation-play-state: initial;

通过编辑动画丰富了动画。

答案 1 :(得分:0)

我想更新classname会更好,例如你有两个类:

.animate {
    width: 100px;
    height: 100px;
    background-color: red;
    position: relative;
    -webkit-animation-name: example; /* Chrome, Safari, Opera */
    -webkit-animation-duration: 4s; /* Chrome, Safari, Opera */
    -webkit-animation-iteration-count: infinite; /* Chrome, Safari, Opera         */
    animation-name: example;
    animation-duration: 1s;
}

.slower{
    animation-duration: 5s;
    animation-iteration-count: infinite;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes example {
    0%   {background-color:red; left:0px; top:0px;}
    25%  {background-color:yellow; left:200px; top:0px;}
    50%  {background-color:blue; left:200px; top:200px;}
    75%  {background-color:green; left:0px; top:200px;}
    100% {background-color:red; left:0px; top:0px;}
}

/* Standard syntax */
@keyframes example {
    0%   {background-color:red; left:0px; top:0px;}
    25%  {background-color:yellow; left:200px; top:0px;}
    50%  {background-color:blue; left:200px; top:200px;}
    75%  {background-color:green; left:0px; top:200px;}
    100% {background-color:red; left:0px; top:0px;}
}

然后用jQuery处理这个问题,如下所示:

$('#ball').click(function () {
    $(this).addClass('slower');
});