我有一个 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/