在拉斐尔需要效率方面的帮助



现在我开始学习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');});
});

}

您可能想要使用类似于集合的东西,并拥有一个自定义函数,该函数内部使用"this"元素,该元素指的是正在使用的对象本身。使用集合或数组,可以轻松地对它们进行迭代。

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

最新更新