2014-09-03 36 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