2016-07-23 12 views
0

jQuery .css()メソッドとdata- *属性を使用してクリックするとCircle要素のCSSプロパティfill(青から赤など)を更新したい。SVG Circle要素でdata- *属性を使用する方法

例:

CSS

svg { 
    height: 200; 
    width: 200; 
} 
circle { 
    fill: blue; 
} 

JAVASCRIPT

jQuery(function(){ 
    $(document).on("click", "[data-update]", function(){ 
    var circle = $(this).find("circle"); 
    circle.css({ fill: "red" }); 
    }); 
}); 

HTML

<svg data-update> 
    <circle cy="100" cx="100" r="50"></circle> 
</svg> 

デモ用のリンクはhereです。

私はdata-update属性に(例えば、緑)の値を追加あれば:

data-update="green" 

を次に特定のどのようなコード私はサークルの要素の色を変更するために変更したり、スクリプト内で追加する必要がありますか?

答えて

0

属性の値を取得するだけで済みます。 Demo

jQuery(function(){ 
    $(document).on("click", "[data-update]", function(){ 
    var circle = $(this).find("circle"); 
    circle.css({ 
     fill: $(this).data('update') // <-- get value 
    }); 
    }); 
}); 

<svg data-update="green"> 
    <circle cy="100" cx="100" r="50"></circle> 
</svg> 
+0

ありがとうございます!出来た! –

0

コードを次のように変更すると結果が得られます。

jQuery(function(){ 
    $(document).on("click", "svg", function(){ 
    var circle = $(this).find("circle"); 
    var color = $(this).data("update"); -- Read the data-update attribute 
    circle.css({ fill: color }); 
    }); 
}); 
+0

ありがとうございます!それも動作します。 –

関連する問題