2016-07-23 82 views
0

我想要使用jQuery .css()方法和data-*屬性單擊它時,更新Circle元素的css屬性fill(例如,從藍色變爲紅色) 。如何在SVG中使用data- *屬性Circle元素

例:

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

是的,謝謝!它也可以。 –

相關問題