Random “start point” for CSS keyframes animation

前端 未结 4 1393
[愿得一人]
[愿得一人] 2021-02-14 06:52

I have a list of boxes with a background image that scrolls vertically with:

@keyframes movie {
   0% { background-position: 50% 5%; }
   50% { background-positi         


        
4条回答
  •  迷失自我
    2021-02-14 07:42

    To elaborate on the suggestion in Chef's answer, the Javascript to randomise the animation delays on a bunch of elements might look something like this:

    var elements = document.querySelectorAll('.movie')
    var animationDuration = 50000; // in milliseconds
    
    // Set the animationDelay of each element to a random value
    // between 0 and animationDuration:
    for (var i = 0; i < elements.length; i++) {
      var randomDuration = Math.floor(Math.random() * animationDuration);
      elements[i].style.animationDelay = randomDuration + 'ms';  
    }
    

    Of course, you can multiply randomDuration by -1 if you want to use negative values for animation delay (so some elements start mid-animation rather than having their initial animation delayed).

提交回复
热议问题