动画背景图像的来回位置

时间:2016-06-08 08:01:17

标签: 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;
}

我的代码不起作用,因为当-100%的背景显示时,我会在0上重新启动。

3 个答案:

答案 0 :(得分:7)

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

  当位置在结尾时,

从左到右,从右到左

对于上述内容,您可以将animation-direction用作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;
}




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

答案 1 :(得分:1)

试试这个

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


    #animate-area   { 
        width: 560px; 
        height: 400px; 
        background-image: url(../pages/bg.jpg);
        background-position: 0px 0px;
        background-repeat: repeat-x;

        animation: animatedBackground 40s linear infinite;
    }

答案 2 :(得分:0)

动画将运行到最后,默认是从头开始。 “动画方向”属性可以处理该问题。以下是一些选项:

正常-默认值。动画正常播放(向前)
反向-动画反向播放(向后)
交替-动画先播放,然后播放 交替反向-动画先向后播放,然后向前播放 initial-将此属性设置为其默认值。
继承-从其父元素继承此属性。

我更喜欢使用替代方法,该方法先运行到末尾,然后再反向返回。

尝试:

@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;
  **animation-direction: alternate**;
}
相关问题