Raphael:如何添加改变颜色的onclick动作?

时间:2011-12-16 13:22:26

标签: javascript html raphael

基于Raphael demo:http://raphaeljs.com/australia.html我创建了改变颜色的对象。但我需要添加动作onclick会改变颜色(橙色)。然后它将保持橙色,直到它再次被点击。

我希望这些对象显示选定的状态(通过具有不同的颜色)。如果单击对象,则会更改颜色。如果再次单击它会恢复正常。再次如果单击它会更改颜色并显示已选中。

这是我的代码的一部分:

            var current = null;
        for (var state in bodyParts) {
            bodyParts[state].color = Raphael.getColor();
            (function (st, state) {
                st[0].style.cursor = "pointer";
                st[0].onmouseover = function () {
                    current && bodyParts[current].animate({ fill: "#EEC7C3", stroke: "#E0B6B2" }, 500) && (document.getElementById(current).style.display = "");
                    st.animate({ fill: st.color, stroke: "#ccc" }, 500);
                    st.toFront();
                    R.safari();
                    document.getElementById(state).style.display = "block";
                    current = state;
                };
                st[0].onmouseout = function () {
                    st.animate({ fill: "#EEC7C3", stroke: "#E0B6B2" }, 500);
                    st.toFront();
                    R.safari();
                };
                st[0].onclick = function () {
                    st.animate({ fill: "#C05219", stroke: "#E0B6B2" }, 500);
                    st.toFront();
                    R.safari();
                };                    
            })(bodyParts[state], state);

点击它会改变颜色,但是当我从对象中取出鼠标后,它会恢复正常并且不会被选中。如何将此“选定”行为添加到此代码中?

1 个答案:

答案 0 :(得分:2)

添加另一个保持所选状态的参数。

   st[0].state = 0;

修改:

            st[0].onclick = function () {
                st.animate({ fill: "#C05219", stroke: "#E0B6B2" }, 500);
                st.toFront();
                R.safari();
            };

像这样:

            st[0].onclick = function () {
                st.animate({ fill: "#C05219", stroke: "#E0B6B2" }, 500);
                st.toFront();
                if (this.state == 0)
                   this.state = 1;
                else
                   this.state = 0;
                R.safari();
            };

而且:

            st[0].onmouseout = function () {
                st.animate({ fill: "#EEC7C3", stroke: "#E0B6B2" }, 500);
                st.toFront();
                R.safari();
            };

像这样:

            st[0].onmouseout = function () {
                if (this.state == 0)
                   st.animate({ fill: "#EEC7C3", stroke: "#E0B6B2" }, 500);
                else
                   st.animate({ fill: "#f00", stroke: "#E0B6B2" }, 500);
                st.toFront();
                R.safari();
            };

当然,用你的颜色......但这是主要的想法。