如何使背景逐渐变色

How to make background gradually change colors?

本文关键字:渐变 背景 何使      更新时间:2023-09-26

我正在尝试制作一个图像背景颜色逐渐变化的网页。我知道如何在Javascript中更改某个东西的背景颜色,但我不知道如何"动画化"(不用Flash)。

您可以使用CSS转换来获得这种效果。只需将css代码添加到从js:更改的元素中即可

-webkit-transition: all 1s ease-in-out;
-moz-transition: all 1s ease-in-out;
-o-transition: all 1s ease-in-out;
-ms-transition: all 1s ease-in-out;
transition: all 1s ease-in-out;

在css上,每次更改任何样式值时,都会将更改从当前值动画化为新值1。

它只适用于现代浏览器。查看示例:单击

下面是一个如何设置body标签背景动画的示例:

function animateBg(i) {
    document.body.style.backgroundColor = 'hsl(' + i + ', 100%, 50%)';
    setTimeout(function() {
        animateBg(++i)
    }, i);
}
animateBg(0);​

请记住,hsl不是交叉浏览器,您也可以使用hex/rgb颜色。

Jsfidle链接:http://jsfiddle.net/euthg/

您可能需要使用setTimeout()函数:

function animateBg()
{
  myElement.style.backgroundColor = someNewValue;
  setTimeout(animateBg, 20); // 20 milliseconds
}

并在身体的onload处理程序中调用animateBg()。例如,<body onload="animateBg()">

我会尝试使用JQuery颜色插件。看看这里的例子(点击Demo),它们似乎正是你所描述的。