【问题标题】:Need help on efficiency in raphael需要帮助提高拉斐尔的效率
【发布时间】:2014-09-03 13:17:08
【问题描述】:

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

}

【问题讨论】:

    标签: arrays loops raphael mouseover


    【解决方案1】:

    您可能想要使用类似集合的东西,并有一个自定义函数,该函数使用其中的“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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-09-26
      • 1970-01-01
      • 2011-06-23
      • 1970-01-01
      • 1970-01-01
      • 2017-04-04
      相关资源
      最近更新 更多