我有一个文本“ HELLO”,我想遍历每个字母并设置动画效果,以使其淡入和淡出。这是我的代码。

编辑:我把答案放在代码片段中,以查看实际效果。

码:



$(document).ready(function() {
  var $letters = $('p[id^="letter-"');
  $letters.each(function(index) {
    $(this).css({
      'animation': 'pulse 500ms ' + index * 500 + 'ms' + ' linear'
    })
  });
});

html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='letter-0'>H</p>
<p id='letter-1'>E</p>
<p id='letter-2'>L</p>
<p id='letter-3'>L</p>
<p id='letter-4'>O</p>





这是pen的链接。
动画不是一次制作一个字母,而是一次对整个动画进行动画处理,如何解决?循环难道不应该完成所有命令的执行,然后继续下一步吗?也许有一种我不知道的更好的方法?

最佳答案

您绝对应该纠正的一件事是id的命名。单个数字是not a valid id

更好的选择是为它们命名,例如letter-0letter-1等。

接下来,可以使用animation-delay属性偏移每个动画的开始。我们将使用速记animation属性。为此,我们将找到每个以id开头的letter-元素,然后循环遍历它们。对于每个连续的字母,我们将添加动画,并在动画中添加500ms *延迟(在字符串中的位置索引)。例如,第一个字母(索引0)的动画延迟为0ms。第二个字母(索引1)的动画延迟为500ms,依此类推。



$(document).ready(function() {
  var $letters = $('p[id^="letter-"');
  $letters.each(function(index) {
    $(this).css({
      'animation': 'pulse 500ms ' + index * 500 + 'ms' + ' linear'
    })
  });
});

html,
body {
  font-size: 45px;
}

p {
  position: absolute;
  left: 400px;
  top: 100px;
  color: rgba(0, 0, 0, 0);
}

@keyframes pulse {
  0% {
    color: rgba(0, 0, 0, 0);
  }
  25% {
    color: rgba(0, 0, 0, 0.5);
  }
  50% {
    color: rgba(0, 0, 0, 1);
  }
  75% {
    color: rgba(0, 0, 0, 0.5);
  }
  100% {
    color: rgba(0, 0, 0, 0);
  }
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p id='letter-0'>H</p>
<p id='letter-1'>E</p>
<p id='letter-2'>L</p>
<p id='letter-3'>L</p>
<p id='letter-4'>O</p>

07-24 18:38
查看更多