cou*_*011 3 javascript raphael
我正在使用Raphael.js库进行特定的工作.我正在创建圈子和绑定悬停事件,显示/隐藏文本.问题是只显示/隐藏了最后一个圆圈上的文字,即使我在其他圆圈上空盘旋.
这是我的代码:
for(var i=0; i<feedData.length; i++){
var x = ((i+1)*diff);
var t = r.text(x, 120, feedData[i].title).hide();
var c = r.circle(x,150,10);
c.attr({fill: "red"});
c.attr({stroke: "red"});
c.attr({title: feedData[i].title});
c.hover(function (event) {
this.animate({r: 13}, 200);
t.show();
}, function (event) {
this.animate({r: 10}, 200);
t.hide();
});
}
Run Code Online (Sandbox Code Playgroud)
对于Raphael.js参考
好吧,我对raphael库一无所知,但看起来你可以将你c.hover的自我调用函数包装起来,以创建一个引用正确值的闭包t.
(function( local_t ) {
c.hover(function (event) {
this.animate({r: 13}, 200);
local_t.show();
}, function (event) {
this.animate({r: 10}, 200);
local_t.hide();
});
})( t );
Run Code Online (Sandbox Code Playgroud)
这样,当你创建hover事件处理程序时,它将传入值的值t,并将其作为局部变量t_local(或者你给它的任何名称)引用它,这将持续到调用处理程序(和之后).
所以完整的代码将是:
for(var i=0; i<feedData.length; i++){
var x = ((i+1)*diff);
var t = r.text(x, 120, feedData[i].title).hide();
var c = r.circle(x,150,10);
c.attr({fill: "red"});
c.attr({stroke: "red"});
c.attr({title: feedData[i].title});
(function( local_t ) {
c.hover(function (event) {
this.animate({r: 13}, 200);
local_t.show();
}, function (event) {
this.animate({r: 10}, 200);
local_t.hide();
});
})( t );
}
Run Code Online (Sandbox Code Playgroud)
编辑:您可以将整个for()语句包含在内部,但我认为这不会对Chrome您在下面的评论中提到的具体问题产生影响.
for(var i = 0; i < feedData.length; i++){
(function( local_i ) {
var x = ( ( local_i + 1) * diff );
var t = r.text(x, 120, feedData[ local_i ].title).hide();
var c = r.circle(x, 150, 10);
c.attr({fill: "red"});
c.attr({stroke: "red"});
c.attr({title: feedData[ local_i ].title});
c.hover(function (event) {
this.animate({r: 13}, 200);
local_t.show();
}, function (event) {
this.animate({r: 10}, 200);
local_t.hide();
});
})( i );
}
Run Code Online (Sandbox Code Playgroud)