在svg路径元素上添加类 [英] Add class on svg path element
问题描述
在我的项目中,我有一个带有不同路径和不同id的SVG世界地图和一个 map-path
类。对于每个国家/地区点击我想在每个路径上添加课程。我的HTML就是这样的:
< svg viewBox =>
<路径id =map_1class =map-path......>
<路径id =map_2class =map-path......>
<! - more< path />元素... - >
< / svg>
JQuery函数 addClass() 在这里不起作用,不能将类添加到SVG中。
使用 .attr() code>代替:
$('body')。on('click','。map-path' ,function(){
$(this).attr(class,map-path newclass);
});
您可以将纯js解决方案与 setAttribute()
方法:
$ $ $''code $('body')。on('click','。map-path',function e){
e.target.setAttribute(class,map-path newclass);
});
或者使用 classList.add()
在现代浏览器中工作:
$('body')。on('click','。map-path',function (e){
e.target.classList.add('newclass');
});
希望这有助于您。
In my project I have an SVG world map with different paths with different id's and one class of map-path
. For each country click I want to add class on each path. My HTML is like this:
<svg viewBox="">
<path id="map_1" class="map-path" ......>
<path id="map_2" class="map-path" ......>
<path id="map_3" class="map-path" ......>
<path id="map_4" class="map-path" ......>
<!-- more <path /> elements... -->
</svg>
JQuery function addClass()
will not work here and can't add a class to an SVG.
Use .attr()
instead :
$('body').on('click','.map-path',function() {
$(this).attr("class", "map-path newclass");
});
You could use pure js solution with setAttribute()
method :
$('body').on('click','.map-path',function(e) {
e.target.setAttribute("class", "map-path newclass");
});
Or use classList.add()
that works in modern browsers :
$('body').on('click','.map-path',function(e) {
e.target.classList.add('newclass');
});
Hope this helps.
这篇关于在svg路径元素上添加类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!