在raphael需要帮助提高效率

时间:2014-09-03 13:17:09

标签: arrays loops raphael mouseover

目前我开始接收javascript,而且我遇到了raphael问题(可能是一般的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');});
});

}

1 个答案:

答案 0 :(得分:0)

你可能想要使用像集合这样的东西,并且有一个使用'这个'其中的元素,指的是正在使用的对象本身。使用集合或数组,您可以轻松地迭代它们。

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