2014-09-03 38 views
0

目前我开始拿起JavaScript,我有一个拉斐尔问题(可能是一般的JavaScript问题)。我需要使代码更紧凑,但我不知道如何。我已经把所有东西放在一个数组中,但我不知道如何让悬停事件更紧凑。在拉斐尔效率需要帮助

这是代码。

window.onload = function() { 
var paper = new Raphael(document.getElementById('holder'), 500, 500); 

var rect1 = paper.rect(50,300,75,75).attr({fill:'#F00'}); 
var rect2 = paper.rect(50,200,75,75).attr({fill:'#0F0'}); 
var rect3 = paper.rect(50,100,75,75).attr({fill:'#00F'}); 
var rect4 = paper.rect(150,100,75,75).attr({fill:'#FF0'}); 
var rect5 = paper.rect(150,200,75,75).attr({fill:'#F0F'}); 
var rect6 = paper.rect(150,300,75,75).attr({fill:'#000'}); 
var rect7 = paper.rect(250,100,75,75).attr({fill:'#0FF'}); 
var rect8 = paper.rect(250,200,75,75).attr({fill:'#F04'}); 
var rect9 = paper.rect(250,300,75,75).attr({fill:'#079'}); 

var Objects; 
Objects.push(rect1, rect2, rect3, rect4, rect5, rect6, rect7, rect8, rect9); 

rect1.mouseover(function(){ 
rect1.animate({opacity:0.5}, 1000, 'bounce', function(){ rect1.animate({opacity:1}, 1000, 'bounce');}); 
}); 
    rect2.mouseover(function(){ 
rect2.animate({opacity:0.5}, 1000, 'bounce', function(){ rect2.animate({opacity:1}, 1000, 'bounce');}); 
}); 
    rect3.mouseover(function(){ 
rect3.animate({opacity:0.5}, 1000, 'bounce', function(){ rect3.animate({opacity:1}, 1000, 'bounce');}); 
}); 
    rect4.mouseover(function(){ 
rect4.animate({opacity:0.5}, 1000, 'bounce', function(){ rect4.animate({opacity:1}, 1000, 'bounce');}); 
}); 
    rect5.mouseover(function(){ 
rect5.animate({opacity:0.5}, 1000, 'bounce', function(){ rect5.animate({opacity:1}, 1000, 'bounce');}); 
}); 
    rect6.mouseover(function(){ 
rect6.animate({opacity:0.5}, 1000, 'bounce', function(){ rect6.animate({opacity:1}, 1000, 'bounce');}); 
}); 
    rect7.mouseover(function(){ 
rect7.animate({opacity:0.5}, 1000, 'bounce', function(){ rect7.animate({opacity:1}, 1000, 'bounce');}); 
}); 
    rect8.mouseover(function(){ 
rect8.animate({opacity:0.5}, 1000, 'bounce', function(){ rect8.animate({opacity:1}, 1000, 'bounce');}); 
}); 
    rect9.mouseover(function(){ 
rect9.animate({opacity:0.5}, 1000, 'bounce', function(){ rect9.animate({opacity:1}, 1000, 'bounce');}); 
}); 

}

回答

0

你可能想使用类似的一组,并且具有使用它里面的“本”元素,它指的是多数民众赞成使用的对象本身的自定义功能。使用set或Array,您可以轻松地遍历它们。

var Objects = paper.set(); 
Objects.push(rect1, rect2, rect3, rect4, rect5, rect6, rect7, rect8, rect9); 

function rectAnimOver() { 
    this.animate({opacity:1}, 1000, 'bounce') 
}; 

function rectAnim() { 
    this.animate({opacity:0.5}, 1000, 'bounce', rectAnimOver) 
}; 

Objects.forEach(function(el) { 
    el.mouseover(rectAnim); 
}); 

jsfiddle