改变内联SVG的颜色

3

我下载了一个世界地图的SVG文件,用Javascript进行SVG操作。我的目标是在点击美国时更改其颜色,再次点击时恢复原始颜色。以下是定义美国的SVG部分:

<path
inkscape:connector-curvature="0"
id="US"
data-name="United States"
data-id="US"
d="m 116.7,450.7 2,-0.9 2.5,-1.4 0.2,-0.4 -0.9,-2.2 -0.7,-0.8 
-7.1,-0.5 -6.2,-1.6 -4.8,0.5 -4.9,-0.9 2,-1.2 -6.3,-0.3 -3.3,1 
0.5,-2.4 z"
style="fill:#f2f2f2;fill-rule:evenodd" />

由于坐标过多导致代码变得冗长,我删掉了大部分坐标。

这是CSS代码:

.united_states {
 fill: blue;
}

以下是使用 JQuery 编写的 JavaScript 代码:

$(function(){
  $('#US').click(function(event){
    console.log("You just clicked on the United States!!");

 $('#US').toggle();
 $(this).toggleClass('.united_states');

  });
})();

最终,这是它的JsFiddle链接:link 将SVG标签的“fill”属性更改为蓝色可行,但我想单击它并切换它(从蓝色到正常状态)。
感谢您的帮助。

2
$obj.toggle()将在blocknone之间切换其display CSS属性。这可能不是您想要的。现在,您在元素的style属性中设置了一个fill规则集。此规则将优先于.united_states类选择器,因此,您的规则不会得到更新。您可以以许多方式安排它,例如不设置style属性而直接设置fill属性,或在全局样式表中设置所有内容,或者(不太好的)通过向规则类的规则添加!important关键字... - Kaiido
可能是img src SVG更改填充颜色的重复问题。 - Vikasdeep Singh
@Kalido 谢谢您的解释! - Logan Phillips
3个回答

1

替换 jQuery 的 toggleClass。相反,您可以使用 classlist 属性,然后切换它。

请参见以下内容:

(function($){
  $('#US').click(function(event){
    console.log("You just clicked on the United States!!");

  $(this).prop("classList").toggle("united_states");
  });
})(jQuery);

CSS:
.united_states {
 fill: blue !important;
}

https://jsfiddle.net/L0r5e2fg/13/


1
这个问题其实不需要另一个回答,但我还是要回答一下,因为你需要做出的更改应该被解释清楚,这样你就知道为什么需要这些更改:
  1. First remove $('#US').toggle();. It was causing that element to be hidden. You don't want that.

  2. Remove the dot/period from your class name in toggleClass(). It is not required here:

    $(this).toggleClass('united_states');
    
  3. However this still doesn't make the toggleClass() work. This is because the map file already has a fill colour defined using a style="" attribute. style attributes have a higher precedence than CSS rules, so your .united_states {...} rule is not doing anything.

    To resolve this, you need to tell the browser that your CSS rule should override the style attribute. You can do this by adding !important to the CSS property:

    .united_states {
      fill: blue !important;
    }
    

工作的fiddle


是的,加上$("#US').toggle();这行代码真的很愚蠢。非常感谢您的帮助,我真的很感激您的解释! - Logan Phillips

0

将您的代码更改为以下内容

JS

$(function(){
  $('#US').click(function(event){
    $(this).toggleClass('united_states');
  });
})();

CSS(层叠样式表)
.united_states {
 fill: blue !important;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接