javascript raphael.js多个对象和事件

javascript raphael.js multiple objects and events

本文关键字:对象 事件 raphael js javascript      更新时间:2023-09-26

我试图通过悬停事件将一个事件链接到一个raphael.js对象,但它不起作用。这是我的代码:

var paper = Raphael('menu', 400, 400);
for(var i = 0; i < 6; i++) {
    var x = 200,
        y = 200;
    var rx = Math.sin(i / 6 * 2 * Math.PI),
        ry = Math.cos(i / 6 * 2 * Math.PI);
    var hx = x + rx * 100,
        hy = y + ry * 100;
    var hexa  = polygon(hx, hy, 6, 50);
    hexa.attr("fill", "rgb(212, 212, 212)");
    hexa.attr("stroke-width", 0);
    var hoverTitle = paper.text(hx + rx * 70, hy + ry * 70, "foo " + i);
    var hoverIn = function() {
        this.animate({fill: "rgb(247,245,240)"}, 300, '<>');
        hoverTitle.show();
        hoverTitle.animate({opacity:1}, 200, '<>');
    }
    var hoverOut = function() {
        this.animate({fill: "rgb(212, 212, 212)"}, 300, '<>');
        hoverTitle.animate({opacity:0}, 200, '<>');
        hoverTitle.hide();
    }
    hexa.hover(hoverIn, hoverOut, hexa, hexa);
}
function polygon(x, y, N, side) {
    var path = "", n, temp_x, temp_y, angle;
    for(n = 0; n <= N; n++) {
        angle = n / N * 2 * Math.PI;
        temp_x = x + Math.cos(angle) * side;
        temp_y = y + Math.sin(angle) * side;
        path += (n === 0 ? "M" : "L") + temp_x + "," + temp_y;
    }
    return paper.path(path);
}

我希望每个六边形在悬停时都显示它的foo,但我不明白为什么它总是指最后一个foo。。。我应该分别申报吗?

这是一个小提琴

之所以会发生这种情况,是因为您将hoverTitle定义为全局变量,所以当您试图在回调中使用它进行操作时,您总是使用最后一个。

解决方案是将hoverTitle定义为每个六边形的局部属性,例如:

hexa.hoverTitle = paper.text(hx + rx * 70, hy + ry * 70, "foo " + i);

然后在回调中使用此属性进行操作:

this.hoverTitle.show();
this.hoverTitle.animate({opacity:1}, 200, '<>');

Fiddle