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

标签 javascript html string toggle raphael

我使用 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/

相关文章:

javascript - 如何让 chrome 自动填充异步帖子

algorithm - 找到与输入最相似的字符串的最快方法?

java - 如何使用java编写字符串的条件逻辑

C:存储调用main时传递的参数

javascript - 如何从终端运行 esnext 文件

javascript - 使用 .map() 生成带有 Refs 的元素

Javascript:围绕特定数字对整数数组进行排序

javascript - 通过单击元素来更改元素的文本。 jQuery

javascript - 包括 HTML 中的 Jquery 库在内的问题

javascript - 使用 onmouseover/onmouseout 更改可见性