彩虹色文本的循环动画

Cycling animation of rainbow-coloured text

本文关键字:循环 动画 文本 彩虹      更新时间:2023-09-26

悬停时循环颜色 使用 JavaScript/jQuery

我正在尝试获取一个文本块,根据 HSL 0 度和 360 度之间的计算位置为每个字母着色,并在悬停时对右侧的颜色进行动画处理。我知道这很奇怪,但请耐心等待。我想要的是悬停时的动画彩虹文本。

我已经介绍了使所有这些发生一次的逻辑,但无法使悬停循环行为正常工作。

这是 codepen.io 的链接:http://cdpn.io/txmlf

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

我真的很感激在这个显然非常重要的项目上的任何帮助。

你可能想考虑一下这将如何影响用户体验,但是这个呢: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(

为什么不保持简单,(只用你的 HTML(这就是你所需要的:

现场演示

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中进行测试