如何为CSS元素设置动画以使其永远移动?

时间:2018-10-01 02:50:02

标签: css css3 css-transforms

我的页面顶部有一个彩虹条:

.rainbow-bar {    /* Epic rainbow bar */
    height:8px;
    background: black; /* fallback */
    background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
    background-size: 200% 200%;
    animation: moveright 3s ease infinite;
    animation-direction: alternate;
}

所以我希望栏永远循环,向右移动。 我不好解释,所以这里是image

这是我当前拥有的动画代码,当然它只是使其移到屏幕外然后再返回,这正是我所不想要的。 如果有人能指出正确的方向,我将非常感谢。

@keyframes moveright {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}

2 个答案:

答案 0 :(得分:0)

在调用颜色时根本不指定背景大小。这是我对您的代码的修改,添加了背景大小,并将关键帧更改为百分比,而不是翻译。

.rainbow-bar {    /* Epic rainbow bar */
    height:8px;
    background: black; /* fallback */
    background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
    background-size: 200% 200%;
    animation: moveright 3s ease infinite;
    animation-direction: alternate;
}

和CSS的动画部分

@keyframes moveright {
    0%{background-position:0% 50%}
    50%{background-position:100% 50%}
    100%{background-position:0% 50%}
}

答案 1 :(得分:0)

因此仅使用CSS来完成此操作有点棘手,但是可以通过更改帧的背景渐变来实现。 Codepen link

HTML:

<div class='bg'>
  <div class='rainbow-bar'>
  </div>
</div>

CSS:

.bg {
    background: black; /* fallback */
}

.rainbow-bar {    /* Epic rainbow bar */
    height: 3px;
    animation: move .75s ease infinite;
}

@keyframes move {
  0% {
    background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
  }
  14.3% {
    background: linear-gradient(to right, violet, red, orange, yellow, green, blue, indigo);
  }
  28.6% {
    background: linear-gradient(to right, indigo, violet, red, orange, yellow, green, blue);
  }
  42.9% {
    background: linear-gradient(to right, blue, indigo, violet, red, orange, yellow, green);
  }
  57.2% {
    background: linear-gradient(to right, green, blue, indigo, violet, red, orange, yellow);
  }
  71.5% {
    background: linear-gradient(to right, yellow, green, blue, indigo, violet, red, orange);
  }
  85.8% { 
    background: linear-gradient(to right, orange, yellow, green, blue, indigo, violet, red);
  }
  100% {
    background: linear-gradient(to right, red, orange, yellow, green, blue, indigo, violet);
  }
}