简体   繁体   English

悬停时随机css动画

[英]random css animation on hover

I have javascript that when hover plays an animation, but i have 4 different animations and i would like it to randomize it each time the element is hovered over 我有javascript,当悬停播放动画,但我有4种不同的动画,我希望它每次元素悬停时随机化

here's my code 这是我的代码

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';


}

The other css animations are bluehover orangehover and purplehover 其他CSS动画是bluehover orangehoverpurplehover

    function getRandomAnimation(duration) {

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

and use it like this: 并像这样使用它:

  document.getElementById('help-box').style.animation = getRandomAnimation('2s)';

Use Math.random to randomize your animations 使用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';
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;
}

You can use Math.Random to get random no between 1 to 4 or either 0 to 3. Here I am getting between 0 to 3 and using a JavaScript array to get the animation 你可以使用Math.Random来获得1到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';

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

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