0

Raphael.jsでいくつかの簡単なボタンを作成しようとしています。だから私は最後のステップで立ち往生しました。これが私のJSFiddle です。ボタンを押した後もボタンはアクティブな状態を維持します。しかし、別のボタンを押すと、押されたボタンを非アクティブにしようとしています。

onclick関数内のループでst.node.state値を取得しようとしましたが、機能していません。これが私のコードです:

for(var i in aus) {

    (function (st) {

        st.node.state = 0;



        st.node.onmouseover = function() {
            st.animate({fill: "#8fbf27", stroke: "#fff"}, 100);
        };
        st.node.onmouseout = function() {
            st.animate({fill: "#555", stroke: "#fff"}, 100);
            if(this.state == 1){
                st.animate({fill: "#fff", stroke: "#fff"}, 100);
            }else {
                st.animate({fill: "#555", stroke: "#fff"}, 100);
            }
        };
        st.node.onclick = function() {

            if(this.state == 0) {
                this.state = 1;
                st.animate({fill: "#fff", stroke: "#fff"}, 100);
            }else {
                this.state = 0;
                st.animate({fill: "#555", stroke: "#fff"}, 100);
            }

        };

    })(aus[i]);
4

1 に答える 1

3

このようなものが機能するはずです。これにより、要素は状態に基づいてアニメーション化されます。クリックすると、要素がアクティブ化されている場合は、ループして他の要素を非アクティブ化します。

// An animator function which will animate based on node state
var animate = function(st) {
  var fill = st.node.state ? "#fff" : "#555";
  st.animate({fill: fill, stroke: "#fff"}, 100);
}

for (i in aus) {
  (function (st) {
    st.node.state = 0;
    st.node.onmouseover = function () {
      if (!this.state) st.animate({fill: "#8fbf27", stroke: "#fff"}, 100);
    };
    st.node.onmouseout = function () {
      animate(st);
    };
    st.node.onclick = function () {
      this.state = 1 - this.state;
      animate(st);
      // if the node is deactivated stop now
      if (!this.state) return;
      // otherwise deactivate and animate the other nodes
      for (i in aus) {
        // if node is `this` or node is already deactivated, continue
        if (aus[i].node === this || !aus[i].node.state) continue;
        // otherwise deactivate and animate
        aus[i].node.state = 0;
        animate(aus[i]);
      }
    };
  }(aus[i]));
}

または、一度に1つだけがアクティブ化される場合は、アクティブ化された1つのノードへの参照を保存するだけで、ループを回避できます。

// A reference to the active element
var activeEl;

// animate based on whether the st is the active element
var animate = function(st) {
  var fill = activeEl === st ? "#fff" : "#555";
  st.animate({fill: fill, stroke: "#fff"}, 100);
}

for (i in aus) {
  (function (st) {
    st.node.onmouseover = function () {
      if (!this.state) st.animate({fill: "#8fbf27", stroke: "#fff"}, 100);
    };
    st.node.onmouseout = function () {
      animate(st);
    };
    st.node.onclick = function () {
      if (!activeEl || activeEl !== st) {
        var el = activeEl;
        activeEl = st;
        if (el) animate(el);
      } else {
        activeEl = null;
      }
      animate(st);
    };
  }(aus[i]));
}
于 2013-03-23T20:26:21.117 に答える