彩虹色文本的循环动画

时间:2013-10-03 17:23:26

标签: javascript jquery css css3 css-animations

使用JavaScript / jQuery循环播放颜色

我正在尝试取一段文字,根据HSL 0deg和360deg之间的计算位置为每个字母着色,然后将颜色悬停在右边的颜色上。我知道这很奇怪,但请耐心等待。 我想要的是悬停时的动画彩虹文字。

我已经涵盖了让所有这一切发生一次的逻辑,但不能让悬停骑行行为发挥作用。

此处是指向codepen.io的链接: http://cdpn.io/txmlf

我尝试过使用JavaScript鼠标事件和jQuery的.hover()。我最初的想法是设置鼠标输入的间隔,并在退出时清除它。

我真的很感谢这个非常重要的项目的任何帮助。

2 个答案:

答案 0 :(得分:17)

你可能想想一下这会如何影响用户体验,但是这个怎么样:http://jsfiddle.net/7Xuep/6/

好的,所以使用CSS动画很容易旋转彩虹的所有颜色。然后问题是将它们链接到所有span标记,以便动画在正确的位置开始。 (即你需要绿色字母从绿色等开始它的动画。)为此,我们可以使用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

答案 1 :(得分:2)

为什么不保持简单,(仅使用您的HTML)这就是您所需要的:

Live demo

var step = 4, // colorChage step, use negative value to change direction
    ms   = 10,  // loop every
    $uni = $('.unicorn'),
    txt  = $uni.text(),
    len  = txt.length,
    lev  = 360/len,
    newCont = "",
    itv;
alert(lev+' '+len);

for(var i=0; i<len; i++)newCont += "<span style='color:hsla("+ i*lev +", 100%, 50%, 1)'>"+ txt.charAt(i) +"</span>";

$uni.html(newCont); // Replace with new content
var $ch = $uni.find('span'); // character

function stop(){ clearInterval(itv); }
function anim(){
  itv = setInterval(function(){
    $ch.each(function(){
      var h = +$(this).attr('style').split(',')[0].split('(')[1]-step % 360;
      $(this).attr({style:"color:hsla("+ h +", 100%, 50%, 1)"});
    });
  }, ms); 
}

$uni.hover(anim,stop);

在FF,Chrome,Opera

中测试
相关问题