如何实现定时渐变效果?

How to have a timed-gradient effect?

我希望圆形边框每 2 秒显示不同的颜色。我希望它是渐变色,这样颜色就不会突出。

JavaScript

setTimeout(function() {
    $(".circle").css("border", "10px solid blue")
}, 2000);

CSS

.circle{
    background-color: #000;
    border-radius: 500px;
    border: 10px solid #FFF;
    color:#fff;
    font-size:20px;
    height: 500px;
    line-height:100px;
    margin: 0px auto;
    text-align:center;
    width: 500px;
}

最简单的方法是使用 setInterval:

var i = setInterval(function () {
    var color = '#' + (Math.random()*0xFFFFFF|0).toString(16);
    // this produces a random hex code
    // taken from http://www.paulirish.com/2009/random-hex-color-code-snippets/
    $(".circle").css("border", "10px solid " + color);
}, 2000);

给它们涂上不同的颜色:

var i = setInterval(function () {
    $(".circle").each(function () {
        var color = '#' + (Math.random()*0xFFFFFF|0).toString(16);
        $(this).css("border", "10px solid " + color);
    })
}, 2000);

fiddle

如果做这样的事情会怎么样...从边框开始并随机更改颜色,但在边框上使用颜色之间的过渡以允许平滑更改。

CSS:

.circle {
    border: 10px solid blue;
}

JAVASCRIPT:

var i = setInterval(function () {
    var color = '#' + ((Math.random()*16777215) | 0).toString(16);
    $(".circle").css({
        transition : 'border-color 2s ease-in-out',
        borderColor: color
    });
}, 2000);

已测试...jsFiddle

如果您想要一个仅 CSS 的解决方案:

您可以使用 CSS animations 随时间更改边框颜色。

HTML

<div></div>

CSS

div {
    width:100px;
    height:100px;
    border-radius:1000px;
    border-width:10px;
    border-style:solid;
    -webkit-animation: changeColor 10s; 
    animation: changeColor 10s;
    -webkit-animation-iteration-count: infinite;
    animation-iteration-count: infinite;
    -webkit-animation-direction: alternate;
    animation-direction: alternate;
}

@-webkit-keyframes changeColor {
    0%   {border-color: red;}
    33%  {border-color: yellow;}
    66%  {border-color: blue;}
    100% {border-color: green;}
}

@keyframes changeColor {
    0%   {border-color: red;}
    33%  {border-color: yellow;}
    66%  {border-color: blue;}
    100% {border-color: green;}
}

这是 final product