如何使动画无限循环地从左向右移动?

时间:2019-01-05 22:54:13

标签: javascript html css css-animations

我的动画当前正以正方形运动。但是,我希望它从屏幕的左侧移动到右侧,然后在无限循环中再次返回。有人可以帮忙吗?

.animation {
  width: 10px;
  height: 10px;
  background-color: red;
  position: relative;
  animation-name: example;
  animation-duration: 4s;
}

@keyframes example {
  0% {
    background-color: red;
    left: 0px;
    top: 0px;
  }
  25% {
    background-color: red;
    left: 200px;
    top: 0px;
  }
  50% {
    background-color: red;
    left: 200px;
    top: 200px;
  }
  75% {
    background-color: red;
    left: 0px;
    top: 200px;
  }
  100% {
    background-color: red;
    left: 0px;
    top: 0px;
  }
}
<div class="animation"></div>

2 个答案:

答案 0 :(得分:1)

您可以将动画的迭代次数设置为infinite,并通过使开始和结束关键帧(0%和100%)共享相同的位置来创建无缝循环,如下所示:

.animation {
  width: 10px;
  height: 10px;
  background-color: red;
  position: relative;
  animation: example 2s infinite;
}

@keyframes example {
  0%,
  100% {
    background-color: red;
    left: 0px;
  }
  50% {
    background-color: red;
    left: 200px;
  }
}
<div class="animation"></div>

答案 1 :(得分:0)

尝试添加animation-iteration-count并将其设置为无限:

    animation-iteration-count: infinite