【问题标题】:Add class on svg path element在 svg 路径元素上添加类
【发布时间】:2016-03-21 11:38:53
【问题描述】:

在我的项目中,我有一个 SVG 世界地图,其中包含不同路径、不同 ID 和一类 map-path。对于每个国家/地区,单击我想在每个路径上添加类。我的 HTML 是这样的:

<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>

【问题讨论】:

  • 针对每个国家/地区点击country 是什么意思? path 标签?
  • 嗨@Zakaria Acharki,我的意思是每个 标签..

标签: jquery html svg


【解决方案1】:

JQuery 函数 addClass() 在此处不起作用,并且无法将类添加到 SVG。

请改用.attr()

$('body').on('click','.map-path',function() {
    $(this).attr("class", "map-path newclass");
});

您可以使用带有setAttribute() 方法的纯 js 解决方案:

$('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');
});

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2012-11-26
    • 2015-10-04
    • 1970-01-01
    • 2019-10-20
    • 1970-01-01
    • 2023-03-03
    • 2020-09-15
    • 2021-10-23
    • 2021-12-01
    相关资源
    最近更新 更多