2011-12-16 49 views
2

基於Raphael demo:http://raphaeljs.com/australia.html我已經創建了改變顏色的對象。但我需要添加行動onclick會改變它的顏色(橙色)。然後它會保持橙色,直到它再次被點擊。Raphael:如何添加改變顏色的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); 

的onclick它改變顏色,但我把鼠標後出來,從對象談到恢復正常,沒有被選中。我如何將這種「選定」行爲添加到此代碼?

回答

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(); 
      }; 

當然,你的顏色......但這是主要的想法。

+0

謝謝!它的工作原理與我想要的完全一樣。 – Marta 2011-12-16 13:58:02