javascript - 刷新div并随机改变文字颜色

标签 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>

最佳答案

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

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

此问题的另一个答案将无效,因为它缺少 Math.floor 调用。

关于javascript - 刷新div并随机改变文字颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23726093/

相关文章:

html - 当我减小浏览器大小时,为什么 "lounge-mobile.css"样式表没有链接?

html - 使列在 Bootstrap 中响应

javascript - 从二进制 1's and 0' s 创建位图/ Canvas 图像以直观地查看 JavaScript 中的数据的算法?

javascript - 滚动时如何向右或向左移动div?

javascript - 将 React prop 传递到 axios.post 时如何绑定(bind) "this"

javascript - 限制计时器重置 JavaScript

javascript - 将气球放在 Canvas 内的任意位置

html - 排列单选按钮

javascript - 字幕文本 - 获取屏幕边界外的文本长度(以像素为单位)

javascript - 点击li在同一页面的iframe中显示内容