刷新div并随机更改文本颜色

时间:2014-05-18 19:39:13

标签: javascript jquery css refresh

我有一个div,在WP中提供一个带有短代码的随机推荐。

<div id="testimonial-refresh"><?php echo do_shortcode('[random-testimonial]'); ?></div>

我有这个脚本每3秒刷新一次div。

<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$("#testimonial-refresh").load(location.href+" #testimonial-refresh>*","");
}, 3000);
</script>

我想知道如何设置5种颜色,并且每次div刷新时文本颜色都会随机变化。

我已经成功设置了它,但它只在窗口重新加载时改变了颜色。我希望它在div重新加载时改变颜色。

谢谢。我一直在寻找两个小时,但没有找到解决方案。

更新

这实际上是照顾它,但它有点小故障:

<script type="text/javascript">

var colors = ['yellow', 'black', 'orange', 'red', 'blue'];

var auto_refresh = setInterval(function () {
    // load another testimonial
    $("#testimonial-refresh").load(location.href+" #testimonial-refresh>*","");
    // change text color randomly
    var rand = Math.floor(Math.random() * colors.length);
    $("#testimonial-refresh").css('color', colors[rand]);
}, 3000);

</script>

2 个答案:

答案 0 :(得分:1)

在该函数中,添加以下代码:

var colors = ["#000", "#00f", "#f00"]; // The list of colors to use
$("#testimonial-refresh").css("color", colors[Math.floor(Math.random()*colors.length)]);

这个问题的另一个答案不会奏效,因为它错过了Math.floor电话。

答案 1 :(得分:0)

var colors = ['yellow', 'black', 'orange', 'red', 'blue'];
var element = $("#testimonial-refresh");

var auto_refresh = setInterval(function () {
    element.load(location.href+" #testimonial-refresh>*", function() {
        // load performed -> change text color randomly
        var rand = Math.floor(Math.random() * colors.length);
        element.css('color', colors[rand]);
    });
}, 3000);

<强>更新

如果你想使用你的脚本,那么这应该有效:

var colors = ['yellow', 'black', 'orange', 'red', 'blue'];

var auto_refresh = setInterval(function () {
    // load another testimonial
    $("#testimonial-refresh").fadeOut(function() {
       $(this).load(location.href + "?ts=" + new Date().getTime() + " #testimonial-refresh>*", "", function() {
            // change text color randomly
            var rand = Math.floor(Math.random() * colors.length);
            $("#testimonial-refresh").css('color', colors[rand]);

            $(this).fadeIn();
        });
    });
}, 3000);
相关问题