在做比较炫酷的现代风格网页时,一个div的颜色可能是动态的,不断变化的。下面来说一下这种效果是如何实现的。
用到的css方法:
(1)linear-gradient:用于设置渐变的颜色:background: linear-gradient(90deg, #496eaa, #944fa8, #a8804f, #496eaa);
其中为了保证颜色变化的连贯性,第一个颜色属性与最后一个颜色属性最好一致(非必须,仅仅是为了满足视觉效果)
(2)animation(IE和google浏览器需要使用-webkit-animation或者-moz-animation):定义颜色渐变的动作。
@keyframes mymove { 0%{ background-position: 0% 0%; } 50%{ background-position: 50% 100%; } 100%{ background-position: 100% 0%; }
}
这是所定义的具体动作。
测试样例源代码:
<!doctype html> <html lang="en"> <head> <style> div{ background: linear-gradient(90deg, #496eaa, #944fa8, #a8804f, #496eaa); background-size:1400% 300%; position:absolute; top:10px; left:10px; animation:mymove 20s ease infinite; -webkit-animation: mymove 20s ease infinite; -moz-animation: mymove 20s ease infinite; } @keyframes mymove { 0% { background-position: 0% 0%; } 50% { background-position: 50% 100%; } 100% { background-position: 100% 0%; } } </style> <meta charset="UTF-8"> <meta name="Generator" content="EditPlus®"> <meta name="Author" content=""> <meta name="Keywords" content=""> <meta name="Description" content=""> <title>Document</title> </head> <body> <div style="width:100%;height:800px"> </div> </body> </html>