定时背景颜色的变化

Timed background color change

本文关键字:变化 颜色 背景 定时      更新时间:2023-09-26

如何将此脚本从jQuery更改为JavaScript?我几乎没有JavaScript的经验,我不知道如何自己改变它。

脚本:

var rotate = function() {$("#Top")
.delay(1000).queue(function() {
    $(this).css({
        "background-color": "red"
    });
    $(this).dequeue();
})
.delay(3000).queue(function() {
    $(this).css({
        "background-color": "green"
    });
    $(this).dequeue();
})
.delay(500).queue(function(next) {
    $(this).css({
        "background-color": "blue"
    });
    $(this).dequeue();
    next();
})
.queue(rotate);
};
rotate();
Html

<div id="Top"></div>

原始:http://jsfiddle.net/h4KL7/1/

John Resig是编写jQuery的人,这里有一个关于JavaScript定时器如何工作的宣传。

我知道它并不完美,可以使用setInterval()clearInterval()来提高效率,但这是一个开始演示

var rotate = function () {
    var el = document.getElementById('Top');
    setTimeout(function () {
        el.style.backgroundColor = 'red';
        setTimeout(function () {
            el.style.backgroundColor = 'green';
            setTimeout(function () {
                el.style.backgroundColor = 'blue';
                rotate();
            }, 500);
        }, 3000);
    }, 1000);
}

更新:添加了一个数组来引用超时id,以确保在时间不同步的情况下不会创建重复。

var rotate = function () {
    var el = document.getElementById('Top');
    var timers = new Array(3);
    function red(el) {
        el.style.backgroundColor = 'red';
        timers[0] = setTimeout(function () { green(el); }, 1000);
        clearTimeout(timers[2]);
    }
    function green(el) {
        el.style.backgroundColor = 'green';
        timers[1] = setTimeout(function () { blue(el); }, 3000);
        clearTimeout(timers[0]);
    }
    function blue(el) {
        el.style.backgroundColor = 'blue';
        timers[2] = setTimeout(function () { red(el); }, 500);
        clearTimeout(timers[1]);
    }
    red(el);
};
rotate();

你的帖子的标题应该是:"我怎么能改变这个从jQuery到CSS";-)

@-webkit-keyframes rainbow {
  0% { background: #FFABAB; }
  20% { background: #FFDAAB; }
  40% { background: #DDFFAB; }
  60% { background: #ABE4FF; }
  80% { background: #D9ABFF; }
  100% { background: #FFABAB; }
}
.top {
  min-height: 200px;
  -webkit-animation: rainbow 10s infinite steps(1);
}

如果你想在背景颜色之间有平滑的过渡,只需省略动画速记属性中的步骤(1)。

看看这个!