动画背景图像的来回位置

ton*_*227 4 css css3 css-animations

我想为我的背景图像添加动画,并在位置结束时从左到右,从右到左重复x.

我的代码:

@keyframes animatedBackground {
  0% { background-position: 0 0; }
  100% { background-position: -100% 0; }
}

body.rotonde{
  background-image: url(../pages/bg.jpg);
  background-repeat: repeat-x;
  animation: animatedBackground 15s linear infinite;
  overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)

我的代码不起作用,因为当背景打开时-100%,我重新启动0.

Har*_*rry 7

你一0到达就重新启动的原因-100%是因为动画一般如何工作.一旦完成循环,它们通常会回到原始状态并重新启动下一个循环.因此,一旦到达-100%(结束状态),它就会将位置重置为0(开始状态).

当位置结束时,从左到右,从右到左

对于上述内容,您可以使用animation-directionas alternate.这将使动画从动画背景的位置0-100%为奇数迭代,然后从-100%0为偶数迭代.

@keyframes animatedBackground {
  0% { background-position: 0 0; }
  100% { background-position: -100% 0; }
}

body{
  background-image: url(http://placehold.it/100x100);
  background-repeat: repeat-x;
  animation: animatedBackground 15s linear alternate infinite;
  overflow: hidden;
}
Run Code Online (Sandbox Code Playgroud)

注意:在上面的代码片段中,它在奇数迭代中从右到左,在偶数迭代中从左到右.如果您需要反过来,只需反转关键帧即可.我的目的只是为了演示交替运动.