[英]Change background color of HTML elements with JavaScript in a certain time period?
我有大约26个html元素,我希望它们在JavaScript中具有以下效果:
有可能做这样的事情吗?
我试图这样做,如下所示:
var j = 2000;
for (i = 1; i <= 26; i++) {
setInterval(function() {document.getElementById('Q' + i).style.backgroundColor = '#00a300'}, j);
setInterval(function() {document.getElementById('Q' + i).style.color = '#FFFFFF'}, j);
j = j + j;
setInterval(function() {document.getElementById('Q' + (i-1)).style.backgroundColor = '#e1e1e1'}, j);
setInterval(function() {document.getElementById('Q' + (i-1)).style.color = '#666666'}, j);
}
我是JavaScript的新手,但从未使用过计时器。
div {
display:block;
background:black;
width:200px;
height:40px;
margin:2px 0px 0px 0px;
}
<div></div><div></div><div></div>....
function animateStuff(domElements, baseColor, activeColor, delay) {
var count=0;
var animationRun=1;
var frames=0;
function frame() {
frames++;
if((frames%delay)==1){//set delay only animate on loops that the set delay has past.
count++;
if(count>=domElements.length){
count=0;//back to the beginning of the loop.
}
// make all the divs black
for(var x=0;x<domElements.length;x++){
domElements[x].style.backgroundColor=baseColor;
}
// make one red
domElements[count].style.backgroundColor=activeColor;
}
if(animationRun){
window.requestAnimationFrame(frame);
}
}
frame();
}
//get an array of elements to animate.
var elements = document.getElementsByTagName("div");
//call animation and pass in the array of elements along with a few color settings and the delay.
animateStuff(elements,"black","red",100);
RequestAnimationFrame()平均会为您提供一致的〜60fps。 当不显示选项卡时,它还会停止动画循环。 显示选项卡时,动画开始。 (frames%delay)==1
会减慢动画的显示速度。
使用此方法的一个很好的例子是我在此处提供了源代码的javascript游戏引擎。 https://github.com/Patrick-W-McMahon/Jinx-Engine
我使用jQuery.animate函数和jQuery颜色插件构造了一个小提琴手示例,以创建背景色的淡入淡出动画。
请在这里找到小提琴: http : //jsfiddle.net/nafm74yd/15/
请注意,jsfiddle的左侧面板中使用了一个外部资源...它指向CDN的jQuery color插件。
该脚本是这样的:
function animate(idx) {
$($('.block')[idx]).animate({ backgroundColor: "#ff0000" }, 200, function () {
var idx2 = idx;
$($('.block')[idx2]).animate({ backgroundColor: "#ffffff" }, 200, function () {});
if (idx >= $('.block').length - 1) {
setTimeout(animate(0), 200);
} else setTimeout(animate(idx + 1), 200);
});
}
$(document).ready(function () {
animate(0);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.