如何获得定时渐变效果?

时间:2015-01-04 03:13:12

标签: javascript css

我想要一个圆形边框,每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;
}

3 个答案:

答案 0 :(得分:1)

最简单的方法是使用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

答案 1 :(得分:1)

如果这样的事情发生了怎么办...从边框开始并随机改变颜色,但在边框上使用颜色之间的过渡以便顺利更改。

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

答案 2 :(得分:1)

如果您想要一个仅限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