您可能想考虑一下这将如何影响用户体验,但是这又如何:http://jsfiddle.net/7Xuep/6/
好的,所以使用 CSS 动画旋转彩虹的所有颜色很容易。然后问题是将它们链接到所有跨度标签,以便动画在正确的位置开始。 (即,您需要绿色字母从绿色等开始动画。)为此,我们可以使用animation-delay:
https://developer.mozilla.org/en-US/docs/Web/CSS/animation-delay
我们可以使用它为每个字母以适当的颜色开始彩虹动画。通过使用linear 计时函数,很容易确定动画将在什么时间到达每种颜色。因此,只需将正确的animation-delay 值附加到每个<span> 元素即可。为此,我只需获取您已经生成的 HTML 并将 CSS 规则添加到每个元素的 style 属性:
var animTime = 6, // time for the animation in seconds
hueChange = 3, // the hue change from one span element to the next
prefixes = ["", "-webkit-", "-moz-", "-o-"],
numPrefixes = prefixes.length;
$('.unicorn').find('span').each(function (i) {
for (var j = 0; j < numPrefixes; j++) {
$(this).css(prefixes[j] + 'animation-delay', (animTime * ((i * hueChange) % 360) / 360) - animTime + 's');
}
});
但您可以在生成所有span 元素的同时执行此操作。
那么这只是一个使用CSS设置动画的例子:
.unicorn:hover span {
animation: colorRotate 6s linear 0s infinite;
}
@keyframes colorRotate {
from {
color: rgb(255, 0, 0);
}
16.6% {
color: rgb(255, 0, 255);
}
33.3% {
color: rgb(0, 0, 255);
}
50% {
color: rgb(0, 255, 255);
}
66.6% {
color: rgb(0, 255, 0);
}
83.3% {
color: rgb(255, 255, 0);
}
to {
color: rgb(255, 0, 0);
}
}
所有这些都将我们带到这里:http://jsfiddle.net/P6WVg/7/
现在,如果您不想在有人不再将鼠标悬停在 .unicorn 上时重置颜色,那么您可以使用 animation-play-state:
https://developer.mozilla.org/en-US/docs/Web/CSS/animation-play-state
但是,我发现 Chrome 在将初始值 -webkit-animation-play-state:paused; 和负值 -webkit-animation-delay 组合在一起时存在问题,因此它只显示第一帧(即在这种情况下为 color: rgb(255,0,0);)。因此,我不得不使用事件监听器在第一次悬停时添加一个包含动画 CSS 的类,这导致我们:
http://jsfiddle.net/7Xuep/6/
(可以在此处跟踪 chrome 中的错误:https://code.google.com/p/chromium/issues/detail?id=269340)