在前面的“setTimeout无效的解决方案”中,有提到一个案件:就是画面中的元素的背景色需要定时进行切换。
之前这个效果也是需要通过setTimeout实现的。不过,最近看到CSS3中有关于动画的介绍,我想了一下,应该也是可以通过动画来实现这个背景切换的效果的。
今天试了一下,果然可以。
demo的代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>animation sample</title>
<style>
.bgClass {
float: left;
width: 50px;
height: 50px;
margin: 2px;
border: 1px solid gray;
}
</style>
<script>
var idx = 1;
var id = "styleForBgColorAnimation";
var bgColorRules = [];
function chgBgColor() {
var startColor;
var endColor;
if(idx == 1 ) {
startColor = "#0f0";
endColor = "#060";
} else if(idx == 2) {
startColor = "#FAA165";
endColor = "#FD6906";
} else if(idx == 3 ) {
startColor = "#040404";
endColor = "#000";
}
// 生成keyframe的名称。
var ruleName = createBgColorRuleName(startColor, endColor);
// 如果keyframe的名称已经存在,则说明此动画已经添加至css中,无须再次添加
// 如果不存在,则新生成动画并添加至画面中
if(bgColorRules.indexOf(ruleName) == -1) {
// 生成keyframe
createBgColorRule(startColor, endColor, ruleName);
// 缓存keyframe名称
bgColorRules.push(ruleName);
}
var tmp = -1;
// 对指定元素应用新生成的动画
for((tmp = idx * 3 - 2); tmp <= idx * 3; tmp++) {
// ruleName 为某个keyframe名称,须已经定义好
// 1.2s 为整个动画所需要时间
// infinite 为无限循环动画
document.querySelector("#bg" + tmp).style.webkitAnimation = ruleName + " 1.2s linear 0s infinite";
}
if(idx++ == 3) {
document.querySelector("#chgBgButton").disabled = true;
}
}
// 根据开始色与终了色生成 keyframe 名称
function createBgColorRuleName(startColor, endColor) {
return ("ChgBgColor-" + startColor.substring(1) + "-" + endColor.substring(1)).toLowerCase();
}
// 根据开始色与终了色生成 动画 内容
function createBgColorRule(startColor, endColor, ruleName) {
var sheet = getStyleById(id);
// 因为整个动画所需要的时间为1.2秒, 此处 0%和50%、51%和100%分别设置成一样的背景色,就是为了让这两个背景色平分这1.2秒
var rule = "@-webkit-keyframes " + ruleName + " { " +
"0% { background: -webkit-gradient(linear, left top, right bottom, from(" + startColor + "), to(" + endColor + "));} " +
"50% { background: -webkit-gradient(linear, left top, right bottom, from(" + startColor + "), to(" + endColor + "));} " +
"51% { background: white;} " +
"100% { background: white;} ";
sheet.insertRule(rule, 0);
}
function getStyleById(styleId) {
var style = document.querySelector("#" + styleId);
if(style) {
return style.sheet;
} else {
var styleSheetElement = document.createElement("style");
styleSheetElement.id = styleId;
return (document.head.appendChild(styleSheetElement)).sheet;
}
}
</script>
</head>
<body>
<div>
<button type="button" id="chgBgButton" οnclick="chgBgColor()">createBgColorRule</button>
</div>
<div>
<div id="bg1" class="bgClass">bg1</div>
<div id="bg2" class="bgClass">bg2</div>
<div id="bg3" class="bgClass">bg3</div>
<div id="bg4" class="bgClass">bg4</div>
<div id="bg5" class="bgClass">bg5</div>
<div id="bg6" class="bgClass">bg6</div>
<div id="bg7" class="bgClass">bg7</div>
<div id="bg8" class="bgClass">bg8</div>
<div id="bg9" class="bgClass">bg9</div>
</div>
</body>
</html>