单击时切换拉斐尔对象的颜色

Toggle raphael object's colour on click

我使用 raphael.js 创建了一个矩形。 var rect = paper.rect(x,y,width,height); 假设 x, y, width 和 height 有一些值。 我想添加一个鼠标单击处理程序,它会在单击时切换矩形的 "fill" 颜色。

除了使用 'if...else...',我如何在点击时在 'red' 和 'green' 之间切换颜色? 将在以下函数中替换 "if...else..." 的内容:

var colour = 'red';
rect.node.onclick = function(){
    if (colour == 'red') colour = 'green';
    else if (colour == 'green') colour = 'red';
    this.setAttribute("fill",colour);
}

更新:

var fill = 'red';
rect.node.onclick = function(){
    fill  = (fill == 'red') ? 'green': 'red';
    console.log(fill);
    this.setAttribute("fill", fill);
}

我现在可以在我的控制台上看到我的填充在红色和绿色之间切换。但它不会改变实际矩形的颜色。

怎么样:

rect.node.onclick = function(){
    var currentColor = this.getAttribute('fill');
    var targetColor = (currentColor === 'red') ? 'green' : 'red';
    this.setAttribute("fill", targetColor);
}

即使没有设置填充颜色,这也应该有效。

感觉如果你在使用 Raphael,那么使用 Graphs 方法是有意义的,并避免像 Raphael 的内部访问器这样的东西,比如 node()。所以你可以将其重写为

rect.click( function() {
    this.attr({ fill: this.attr('fill') == 'green' ? 'red' : 'green' }); 
});