【问题标题】:Refresh div and randomly change text color刷新 div 并随机更改文本颜色
【发布时间】:2014-07-06 17:24:42
【问题描述】:

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

【问题讨论】:

    标签: javascript jquery css refresh


    【解决方案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 调用。

    【讨论】:

      【解决方案2】:
      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-10-08
        • 1970-01-01
        • 2012-02-17
        • 1970-01-01
        • 1970-01-01
        • 2013-04-22
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多