javascript 如何让背景逐渐变色?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9369365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make background gradually change colors?
提问by Isaiah Bugarin
I'm trying to make a web page where the background color of an image gradually changes colors. I know how to change the background color of something in Javascript, but I don't know how to "animate" it so to speak (without using Flash).
我正在尝试制作一个网页,其中图像的背景颜色逐渐改变颜色。我知道如何在 Javascript 中更改某些东西的背景颜色,但我不知道如何“动画”它可以这么说(不使用 Flash)。
回答by MarcinJuraszek
You can use CSS transitions to get that effect. Just add that css code into the element that is changed from js:
您可以使用 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;
With that on css each time any style value is being changed that change is animated from current to new value by 1s.
每次更改任何样式值时,css 都会以 1 秒的速度从当前值动画更改为新值。
It works only on modern browsers. See an example: click
它仅适用于现代浏览器。查看示例:单击
回答by Adrien Schuler
Here is an example on how to animate the body tag background :
这是一个关于如何为 body 标签背景设置动画的示例:
function animateBg(i) {
document.body.style.backgroundColor = 'hsl(' + i + ', 100%, 50%)';
setTimeout(function() {
animateBg(++i)
}, i);
}
animateBg(0);?
Keep in mind that hsl isn't crossbrowser, you can also do the trick with hex/rgb colors.
请记住,hsl 不是跨浏览器,您也可以使用 hex/rgb 颜色来解决这个问题。
Jsfiddle link : http://jsfiddle.net/euthg/
jsfiddle 链接:http: //jsfiddle.net/euthg/
回答by Alexander Pavlov
You might want to use the setTimeout()
function:
您可能想要使用该setTimeout()
功能:
function animateBg()
{
myElement.style.backgroundColor = someNewValue;
setTimeout(animateBg, 20); // 20 milliseconds
}
and invoke animateBg() in your body's onload
handler. E.g., <body onload="animateBg()">
.
并在您的身体onload
处理程序中调用 animateBg() 。例如,<body onload="animateBg()">
。
回答by mck
I would try using a JQuery color plugin. Look at the examples here(click on Demo), they seem to do exactly what you describe.
我会尝试使用JQuery 颜色插件。看看这里的例子(点击演示),它们似乎完全符合你的描述。