【问题标题】:jQuery animate background color. Remove Math.randomjQuery 动画背景颜色。删除 Math.random
【发布时间】:2016-11-29 14:26:08
【问题描述】:

我想在一组背景颜色之间制作动画。

我找到了以下代码,但它使用 Math.random 以随机顺序显示背景颜色。

$(document).ready(function() {  
    setInterval(function() {
        var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
        var theColour = theColours[Math.floor(Math.random()*theColours.length)];
        $('#branding').animate({backgroundColor: theColour}, 500);
    }, 1000);
}); 

JSFiddle

我想删除 Math.random 并显示数组中的下一个颜色。

但是,如果我将 Math.random 替换为以下内容,则动画不会超出数组中的第一种颜色。

$(document).ready(function() {  
    setInterval(function() {
        var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
        var currentColour = 0;
        var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
        $('#branding').animate({backgroundColor: theColour}, 500);
    }, 1000);
}); 

【问题讨论】:

    标签: javascript jquery html css random


    【解决方案1】:

    因为currentColour 是在setInterval 函数中声明的,所以每次调用该函数时,您都会创建一个新的currentColour 变量并将其设置为0。而是将currentColour 移到函数范围之外:

    $(document).ready(function() {
        var currentColour = 0; // This variable is now shared by each function call
        setInterval(function() {
            var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
            var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
            $('#branding').animate({backgroundColor: theColour}, 500);
        }, 1000);
    }); 
    

    【讨论】:

      【解决方案2】:

      问题是您在代码本身中重新初始化“theColour”。

      $(document).ready(function() {  
      var currentColour = 0;
          setInterval(function() {
              var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');            
              var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
              $('#branding').animate({backgroundColor: theColour}, 500);
          }, 1000);
      });
      

      【讨论】:

        【解决方案3】:

        你需要在 setInterval 函数之外定义 currentColour

        $(document).ready(function() { 
        		var currentColour = 0;
            setInterval(function() {
                var theColours = Array('#ffffff','#000000','#00ff00','#ff0000','#0000ff');
                var theColour = theColours[Math.floor(currentColour++ % theColours.length)];
                $('#branding').animate({backgroundColor: theColour}, 500);
            }, 1000);
        }); 

        【讨论】:

          猜你喜欢
          • 2023-03-11
          • 2010-09-16
          • 1970-01-01
          • 1970-01-01
          • 2010-11-20
          • 1970-01-01
          • 1970-01-01
          • 2015-08-11
          • 1970-01-01
          相关资源
          最近更新 更多