jQuery动画背景颜色.删除Math.random
jQuery animate background color. Remove Math.random
我想在一组背景颜色之间设置动画。
我找到了以下代码,但它使用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);
});
因为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);
});
问题是您正在初始化代码本身中的"颜色"。
$(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);
});
您需要定义currentColour函数外的setInterval
$(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);
});
相关文章:
- 如何使一个Math.random数组元素比另一个数组元素更有可能被选中
- Math.random不断返回相同的答案
- JS:如何在使用 Math.random() 时排除一系列值
- Javascript;使用math.random函数随机执行一个操作
- Math.random()如何在javascript中工作
- for loop, Math.random() 不按预期运行
- 在 jQuery 中的 Math.random() 之后找到 “li”
- Math.floor(Math.random()) +1 实际上做了什么
- 掷骰子脚本均匀分布吗?(使用 Math.random())
- 带有 php 变量的 Math.random javascript
- 你如何使 Math.random 数组中的每一个第 9 个元素都是同一个元素?[JavaScript]
- Java - ScriptEngineManager nashorn Math.random 不起作用
- 无法正确使用Math.random
- 增加Math.random中某个数字在一定范围内的机会
- 如何将 Math.random() 方法生成的当前值与以前的值进行比较
- Javascript单选按钮鼠标悬停在移动图像上,使用math.random
- Math.Random在函数中总是相同的结果
- 如何在 JavaScript 中使用 Math.random 进行测试
- 谷歌地图API使用Math.random获取随机位置 - JS
- (Math.random()*x)+y 返回大于 x+y 的数字