在特定时间段内使用 JavaScript 更改 HTML 元素的背景颜色?

2024-04-07

我有大约 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 新手,从未使用过计时器。


css

div {
    display:block;
    background:black;
    width:200px;
    height:40px;
    margin:2px 0px 0px 0px;
}

html

<div></div><div></div><div></div>....

js

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 https://github.com/Patrick-W-McMahon/Jinx-Engine

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在特定时间段内使用 JavaScript 更改 HTML 元素的背景颜色? 的相关文章