基于值的背景颜色淡入淡出

时间:2014-01-26 22:43:09

标签: jquery

我正在尝试使用Jquery动画功能来更改div的背景颜色。如果随机数低于50则为红色,如果高于50则为绿色。除了颜色变化外,一切似乎都有效。我在这里做错了什么?

function randomInt(min,max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

if (randomInt(1, 100) > 50) {
    $('#status').html("win").animate({backgroundColor: "green" }, "fast");
} else {
    $('#status').html("lose").animate({ backgroundColor: "red" }, "fast");
}

4 个答案:

答案 0 :(得分:0)

您需要使用jQuery UI或特殊颜色插件来设置颜色动画 - 与大多数其他CSS属性不同。

http://plugins.jquery.com/color/

答案 1 :(得分:0)

可能不是使用jQuery animate()而是使用CSS3 transition

CSS:

#status {
    -webkit-transition: background-color 2000ms linear;
    -moz-transition: background-color 2000ms linear;
    -o-transition: background-color 2000ms linear;
    -ms-transition: background-color 2000ms linear;
    transition: background-color 2000ms linear;
 }

jQuery的:

function randomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}

if (randomInt(1, 100) > 50) {
    $('#status').html("win").css({
        backgroundColor: "green"
    });
} else {
    $('#status').html("lose").css({
        backgroundColor: "red"
    });
}

请参阅此jsfiddle

但如果您真的希望使用纯jQuery执行此操作,则可以使用比整个UI库更轻的jQuery Color

答案 2 :(得分:0)

如果您不想使用Jquery UI或特殊插件。 **只是想展示“绿色”或“红色”颜色,然后还有其他可行的解决方案:

function randomInt(min,max) {
    return Math.floor(Math.random() * (max - min + 1) + min);
}
var status = $('#status');
if (randomInt(1, 100) > 50) {
    status.append("win");
    status.css({backgroundColor: 'green'});
} else {
    status.append("lose");
    status.css({backgroundColor: 'red'});
}

答案 3 :(得分:0)

为什么不用简单的JavaScript和CSS来做呢?

只需将transition: background 1s添加到CSS并使用getElementById中的JavaScript

这是Fiddle