2016-07-23 32 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

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

相关问题