我试图使用for循环和rgb()值连续更改div标签的背景.以下是我在sample.html中编写的代码:
<!DOCTYPE html>
<html lang="en">
<head>
<title>sample</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script >
<script>
$(document).ready(function(){
var r=0;
var g=0;
var b=0;
for(r=0;r<255;r++)
{
for(g=0;g<255;g++)
{
for(b=0;b<255;b++)
{
$("#sqr").css("background-color","rgb(r,g,b)");
}
}
}
});
</script>
<style>
#sqr{background-color:rgb(255,0,0);
height:200px;
width:200px;
}
</style>
</head>
<body>
<div id="sqr">
</div>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)
所以可以enyone告诉我应该如何制作代码,以便div的背景颜色在页面加载时自动更改?请注意,我想非常顺利地改变颜色.
如果你想看看我想要的效果,那么访问:在这里,看看它显示的效果.
根据一些建议,我已将代码更改为:
$("#sqr").css("background-color","rgb("+r+","+g+","+b+")");
Run Code Online (Sandbox Code Playgroud)
现在它正确地获取了rgb的值,但没有在浏览器中正确加载效果,显示对话框:

由于这个问题被标记为CSS,我想为此贡献一个纯CSS解决方案,只需使用CSS3 @keyframes,您可以简单地为您想要的元素添加颜色,可以使用步骤动画%,也可以使用animation-iteration-count并设置为infinite.如果你想在有限的时间内迭代它,只需将其infinite改为你想要的任何值,但要确保它是一个整数.
.animate {
height: 200px;
width: 400px;
border: 1px solid #000;
-webkit-animation: animate_bg 5s;
animation: animate_bg 5s;
-webkit-animation-iteration-count: infinite;
animation-iteration-count: infinite;
}
@keyframes animate_bg {
0% {background:red;}
50% {background:green;}
100% {background:blue;}
}
@-webkit-keyframes animate_bg {
0% {background:red;}
50% {background:green;}
100% {background:blue;}
}
Run Code Online (Sandbox Code Playgroud)
这是在CSS3规范中引入的,因此您可以参考此链接以获得浏览器支持.
有许多polyfills可供其不支持CSS3的浏览器@keyframes,所以你可能需要使用这个,如果你正在寻找支持旧的浏览器,如果你不关心老的,比你可以用这个没有任何犹豫.
| 归档时间: |
|
| 查看次数: |
10081 次 |
| 最近记录: |