11

我有一个带有垂直滚动背景图像的框列表:

@keyframes movie {
   0% { background-position: 50% 5%; }
   50% { background-position: 50% 95%; }
   0% { background-position: 50% 5%; }
}

.movie {
    animation: movie 50s linear infinite;
}

“问题”是这样所有的盒子都有背景同时移动。
我想要一个“随机起点”,这样每个盒子都有不同的动画。

例如,一个背景向下移动,而另一个背景向上移动。

纯CSS可以吗?我也找不到使用 Javascript 的简单方法。

4

4 回答 4

20

您可以使用负动画延迟。

https://developer.mozilla.org/en-US/docs/Web/CSS/animation-delay

为动画延迟指定负值会导致动画立即开始执行。但是,它似乎已经在其周期的中途开始执行。例如,如果您将 -1s 指定为动画延迟时间,则动画将立即开始,但会在动画序列的 1 秒后开始。

因此,如果您希望动画从 20% 开始,动画延迟将为 (-50s * 20%)。您只需要使用 javascript 创建随机起点。

于 2013-10-09T11:50:41.560 回答
8

您可以使用animation-delay.

animation-delay: 10s;

或者在你的速记中:

animation: movie 50s linear 10s infinite;

使用一些伪类可能更容易处理:

.movie:nth-of-type(1) {
  animation-delay: 10s;
}

.movie:nth-of-type(2) {
  animation-delay: 20s;
}

.movie:nth-of-type(3) {
  animation-delay: 30s;
}
于 2013-10-09T10:37:46.190 回答
3

这可以使用纯 CSS 来完成,无需编写(或通过 SCSS 等生成),使用以下组合:

  • animation-delay改变动画开始时间的负数
  • 多个nth-childnth-of-type规则来应用将“随机化”规则应用的公式
movie.nth-child(2n) { animation-delay: -10s }  
movie.nth-child(2n+1) { animation-delay: -30s }  
movie.nth-child(3n) { animation-delay: -20s; }  
movie.nth-child(5n) { animation-delay: -40s }  
movie.nth-child(7n) { animation-delay: -15s }  
{etc}

仅使用前 2 条规则会给出交替规则(例如表中的偶数/奇数行)。请注意第二条具有+1偏移量的规则 - 如果您的类 ( movie) 没有适合您正在更改的规则的默认值(默认情况下为 0),这很重要animation-delay

使用nth-child(n)具有素数倍数的公式n使有效模式长度等于所有素数的乘积(例如2*3*5*7 = 210重复之前的元素)。

li {
  animation: movie 5s linear infinite;
}
@keyframes movie {
  20% { color: white }
  40% { color: black }
}
li:nth-child(2n-1) {
  background-color: lime;
  animation-delay: 1s;
}
li:nth-child(2n) {
  background-color: orange;
  animation-delay: 2s;
}
li:nth-child(3n) {
  background-color: yellow;
  animation-delay: 3s;
}
li:nth-child(5n) {
  background-color: magenta;
  animation-delay: 5s;
}
li:nth-child(7n) {
  background-color: aqua;
}
<ul>
  <li>0</li>
  <li>1</li>
  <li>2</li>
  <li>3</li>
  <li>4</li>
  <li>5</li>
  <li>6</li>
  <li>7</li>
  <li>8</li>
  <li>9</li>
  <li>10</li>
  <li>11</li>
  <li>12</li>
  <li>13</li>
</ul>

为了进一步随机化,您可以创建第二组规则,其n倍数/偏移量略有不同,并更改animation-duration(或任何其他规则)。

于 2016-09-09T17:09:30.910 回答
1

为了详细说明 Chef's answer中的建议,用于随机化一堆元素上的动画延迟的 Javascript 可能如下所示:

var elements = document.querySelectorAll('.movie')
var animationDuration = 50000; // in milliseconds

// Set the animationDelay of each element to a random value
// between 0 and animationDuration:
for (var i = 0; i < elements.length; i++) {
  var randomDuration = Math.floor(Math.random() * animationDuration);
  elements[i].style.animationDelay = randomDuration + 'ms';  
}

当然,randomDuration如果你想对动画延迟使用负值,你可以乘以 -1(所以一些元素在动画中间开始,而不是让它们的初始动画延迟)。

于 2016-10-04T19:38:59.363 回答