1

我有javascript,当悬停播放动画时,我有4个不同的动画,我希望它在每次元素悬停时随机化它

这是我的代码

function firsthelp() { 

document.getElementById('help-text').innerHTML = 'Enter your first name';
  document.getElementById('help-box').style.animation ='greenhover 2s;';
  document.getElementById('help-box').style.WebkitAnimation ='greenhover 2s';


}

其他 css 动画是bluehover orangehoverpurplehover

4

4 回答 4

2
    function getRandomAnimation(duration) {

      var possibleAnimations = ["greenhover","bluehover","orangehover","purplehover"];
      var randomNumber = Math.floor((Math.random()*4));
      return (possibleAnimations[randomNumber] + " " + duration || "");
    }

并像这样使用它:

  document.getElementById('help-box').style.animation = getRandomAnimation('2s)';
于 2013-04-25T11:50:01.103 回答
1

使用Math.random随机化你的动画

var randomNumber = Math.floor((Math.random()*4)+1);
var hover;
if(randomNumber == 1)
{
    hover = 'greenhover'
}
else if(randomNumber == 2)
{
    hover = 'purplehover';        
}
else if(randomNumber == 3)
{
    hover = 'orangehover';        
}
else if(randomNumber == 4)
{
    hover = 'bluehover';        
}

document.getElementById('help-text').innerHTML = 'Enter your first name';
document.getElementById('help-box').style.animation =hover +' 2s;';
document.getElementById('help-box').style.WebkitAnimation =hover +' 2s';
于 2013-04-25T11:43:03.870 回答
0

您可以使用Math.Random1 到 4 或 0 到 3 之间的随机数。这里我得到 0 到 3 之间并使用 JavaScript 数组来获取动画

var animations = new Array();
animations[0] = "greenhover";
animations[1] = "bluehover";
animations[2] = "orangehover";
animations[3] = "purplehover";

var randomNo = Math.floor(Math.random() * 4);

document.getElementById('help-text').innerHTML = 'Enter your first name';
document.getElementById('help-box').style.animation =animations[randomNo] +' 2s;';
document.getElementById('help-box').style.WebkitAnimation =animations[randomNo]+' 2s';
于 2013-04-25T11:52:50.847 回答
0
function firsthelp() { 

document.getElementById('help-text').innerHTML = 'Enter your first name';
  var random_animation = ["greenhover", "bluehover", "orangehover", "purplehover"];
  var number = Math.random();
  var animation = random_animation[Math.floor(number * 4)] + " 2s";
  document.getElementById('help-box').style.animation = animation;
}
于 2013-04-25T11:47:22.187 回答