【问题标题】:Changing color of an inline SVG更改内联 SVG 的颜色
【发布时间】:2018-07-13 16:52:35
【问题描述】:

我下载了一个世界地图 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;
}

这里是javascript,使用JQuery:

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

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

  });
})();

最后,这是一个 JsFiddle:link

将标签的“填充”属性更改为蓝色有效,但我想在点击时进行,然后切换它(蓝色然后恢复正常)。

感谢您的帮助。

【问题讨论】:

  • $obj.toggle() 将在blocknone 之间切换其display CSSProperty。可能不是你想要的。现在,您确实在元素的style 属性中设置了fill 规则。此规则将优先于 .united_states 类选择器,因此您的规则不会得到更新。您可以通过多种方式安排它,例如不直接设置style 属性而是直接设置fill 属性,或者将其全部设置在全局样式表中,或者(不太好)通过将!important 关键字添加到规则类的规则。 ..
  • @Kalido 谢谢你的解释!

标签: javascript jquery html css svg


【解决方案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/

【讨论】:

    【解决方案2】:

    这个问题并不需要另一个答案,但我这样做是因为应该解释您需要进行的更改,因此您知道为什么需要它们:

    1. 首先删除$('#US').toggle();。它导致该元素被隐藏。你不想这样。

    2. toggleClass() 中的班级名称中删除点/句点。这里不需要:

      $(this).toggleClass('united_states');
      
    3. 但这仍然不能使toggleClass() 工作。这是因为地图文件已经使用style="" 属性定义了填充颜色。 style 属性的优先级高于 CSS 规则,因此您的 .united_states {...} 规则没有做任何事情。

      要解决这个问题,您需要告诉浏览器您的 CSS 规则应该覆盖 style 属性。您可以通过在 CSS 属性中添加 !important 来做到这一点:

      .united_states {
        fill: blue !important;
      }
      

    Working fiddle

    【讨论】:

    • 是的,有 $("#US').toggle(); 行是愚蠢的。感谢您的帮助,非常感谢您的解释!
    【解决方案3】:

    把你的代码改成这个

    JS

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

    CSS

    .united_states {
     fill: blue !important;
    }
    

    【讨论】:

      猜你喜欢
      • 2016-10-22
      • 2020-10-30
      • 1970-01-01
      • 2015-02-25
      • 2022-01-25
      • 2020-09-27
      • 1970-01-01
      • 2021-10-31
      • 2016-07-15
      相关资源
      最近更新 更多