Css动画随机延迟



我正试图为一家漫画工作室建立一个网页,我希望每隔一段时间就有一个角色出现在旁边。到目前为止,我在css 中有这个

        .charc {
            animation:peek 20s infinite;
            left:-500px
        }
        @-webkit-keyframes peek{
            1% {transform:translateX(-500px)}
            10%{transform:translateX(100px)}
            20% {transform:translateX(-200px)}
            100% {transform:translateX(-500px)}
        }

和html

<img src="character.jpg" class="charc"/>

这意味着这个角色一次又一次地出现。我不知道是否有可能在CSS中获得随机数字,但我想如果是的话,你们会知道的

附言:我知道这只适用于铬,但我很快就会改变。

您需要使用js/jQuery。

    function move() {
      $('.charc')
        .animate({
          left: '-500px'
        }, 200)
        .animate({
          left: '100px'
        }, 400)
        .animate({
          left: '50px'
        }, 400)
        .animate({
          left: '-500px'
        }, 100, function() {
          var nextIn = Math.floor(Math.random() * 1000);
          setTimeout('move()', nextIn);
        })
    }
    $(document).ready(function() {
      move();
    });
#scene {
  width: 500px;
  height: 100px;
  border: 2px solid black;
  margin: 20px;
}
.charc {
  position: absolute;
  left: -500px;
  top: 20px;
  width: 20px;
  height: 20px;
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="scene">
  <div class="charc"></div>
</div>

js:是可能的

    var divElement = document.getElementsByClassName("charc")[0];
    var maxValue = 20; //the random value won't exceed 20s
    function randomTime(maxvalue){
      return Math.round(Math.random() * maxvalue );
    }
    function changeAnimationTime(maxValue){
       var random = randomTime(maxValue);
       divElement.style.animation = "peek "+randomTime+"s infinite";
       setTimeout(function(){
           changeAnimationTime(maxValue);
       },random);
    }
    changeAnimationTime(maxValue);

这种方法的优点是,您不会将js用于动画,而只是用于生成值。因此,它消耗的资源更少。

不是随机延迟,但您可以使用我创建的名为WAIT的工具!Animate可在动画之间添加暂停。这是你的动画,动画之间有2秒的停顿:

.peek.wait2.animated {
  animation: peek-wait2 22s linear infinite;
  transform-origin: 50% 50%
}
@keyframes peek-wait2 {
  0% { transform:translateX(-500px) }
  9.09091% { transform:translateX(100px) }
  18.18182% { transform:translateX(-200px) }
  90.90909% { transform:translateX(-500px) }
  100% { transform:translateX(-500px) }
}

使用WAIT!设置动画以更改暂停持续时间。

PS。我建议从0%开始,以避免动画中出现闪烁。

最新更新