日期:2014-05-16  浏览次数:20478 次

求帮我优化下这段代码
function face(){
if(document.getElementById("bq01")){
var ctx1 = document.getElementById("bq01").getContext('2d');}
if(document.getElementById("bq02")){
var ctx2 = document.getElementById("bq02").getContext('2d');}
if(document.getElementById("bq03")){
var ctx3 = document.getElementById("bq03").getContext('2d');}
if(document.getElementById("bq04")){
var ctx4 = document.getElementById("bq04").getContext('2d');}
if(document.getElementById("bq05")){
var ctx5 = document.getElementById("bq05").getContext('2d');}
if(document.getElementById("bq06")){
var ctx6 = document.getElementById("bq06").getContext('2d');}
if(document.getElementById("bq07")){
var ctx7 = document.getElementById("bq07").getContext('2d');}
if(document.getElementById("bq08")){
var ctx8 = document.getElementById("bq08").getContext('2d');}
if(document.getElementById("bq09")){
var ctx9 = document.getElementById("bq09").getContext('2d');}
if(document.getElementById("bq10")){
var ctx10 = document.getElementById("bq10").getContext('2d');}
if(document.getElementById("bq11")){
var ctx11 = document.getElementById("bq11").getContext('2d');}
if(document.getElementById("bq12")){
var ctx12 = document.getElementById("bq12").getContext('2d');}
var ctx,img;
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
var img4 = new Image();
var img5 = new Image();
var img6 = new Image();
var img7 = new Image();
var img8 = new Image();
var img9 = new Image();
var img10 = new Image();
var img11 = new Image();
var img12 = new Image();
var speed = 150;
function image(ctx,img){
function drawStar(){
for(var i = 0; i < 6; i++ ){
draw(i);
}
function draw(x){
setTimeout(function(){
ctx.clearRect(0,0,60,70);
ctx.drawImage(img,0,70*x,60,70,0,0,60,70);
},speed*x);
}
}
setInterval(drawStar,900);
}
if(ctx1){
img1.src = 'themes/images/imgd/biaoqing01.png';
img1.onload = image(ctx1,img1);
}
if(ctx2){
img2.src = 'themes/images/imgd/biaoqing02.png';
img2.onload = image(ctx2,img2);
}
if(ctx3){
img3.src = 'themes/images/imgd/biaoqing03.png';
img3.onload = image(ctx3,img3);
}
if(ctx4){
img4.src = 'themes/images/imgd/biaoqing04.png';
img4.onload = image(ctx4,img4);
}
if(ctx5){
img5.src = 'themes/images/imgd/biaoqing05.png';
img5.onload = image(ctx5,img5);
}
if(ctx6){
img6.src = 'themes/images/imgd/biaoqing06.png';
img6.onload = image(ctx6,img6);
}
if(ctx7){
img7.src = 'themes/images/imgd/biaoqing07.png';
img7.onload = image(ctx7,img7);
}
if(ctx8){
img8.src = 'themes/images/imgd/biaoqing08.png';
img8.onload = image(ctx8,img8);
}
if(ctx9){
img9.src = 'themes/images/imgd/biaoqing09.png';
img9.onload = image(ctx9,img9);
}
if(ctx10){
img10.src = 'themes/images/imgd/biaoqing10.png';
img10.onload = image(ctx10,img10);
}
if(ctx11){
img11.src = 'themes/images/imgd/biaoqing11.png';
img11.onload = image(ctx11,img11);
}
if(ctx12){
img12.src = 'themes/images/imgd/biaoqing12.png';
img12.onload = image(ctx12,img12);
}
}

------解决方案--------------------
用for循环呀,很简单的
------解决方案------