我使用 raphael.js 创建了一个矩形。
var rect = paper.rect(x,y,width,height);
假设 x、y、width 和 height 有一些值。
我想添加一个鼠标单击处理程序,该处理程序将在单击时切换矩形的“填充”颜色。
除了使用“if...else...”之外,如何在单击时在“红色”和“绿色”之间切换颜色? 将替换以下函数中的“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);
}
即使没有设置填充颜色,这也应该有效。
关于javascript - 单击时切换拉斐尔对象的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30908932/