【问题标题】:Find and replace color on button click with jQuery使用 jQuery 查找和替换按钮单击时的颜色
【发布时间】:2020-04-05 16:06:27
【问题描述】:

我有一个包含多个 linearGradient 元素的 SVG,我想在按下按钮时将整个 SVG 中的 #4D4D4D 值更改为 #ff0000

有没有办法在整个 SVG 中搜索值并替换成我想要的颜色?

<svg>
  <g id="Group_Volute_Chamber">

    <linearGradient id="SVGID_2_" gradientUnits="userSpaceOnUse" x1="6.8694" y1="93.75" x2="30.2922" y2="93.75" gradientTransform="matrix(1 0 0 -1 0 112.5)">
      <stop offset="0.01" stop-color="#4D4D4D" />
      <!--4d4d4d  style="stop-color:#4F4D4D"-->
      <stop offset="0.51" style="stop-color:#F5F5F5" />
      <stop offset="1" style="stop-color:#4D4D4D" />
    </linearGradient>
    <path fill="url(#SVGID_2_)" stroke="#4C4C4C" stroke-width="0.25" d="M6.869,3.266V37.5h23.423v-0.45V3.266l-1.577-2.703L27.59,0   h-0.676h-1.239H10.248L7.545,1.577L6.982,2.703L6.869,3.266" />

    <linearGradient id="SVGID_3_" gradientUnits="userSpaceOnUse" x1="6.8694" y1="78.1523" x2="30.2922" y2="78.1523" gradientTransform="matrix(1 0 0 -1 0 112.5)">
      <stop offset="0.01" style="stop-color:#4D4D4D" />
      <stop offset="0.51" style="stop-color:#F5F5F5" />
      <stop offset="1" style="stop-color:#4D4D4D" />
    </linearGradient>
    <path fill="url(#SVGID_3_)" stroke="#4C4C4C" stroke-width="0.25" d="M6.869,34.347h23.423" />

    <linearGradient id="SVGID_4_" gradientUnits="userSpaceOnUse" x1="6.8694" y1="105.8555" x2="30.2922" y2="105.8555" gradientTransform="matrix(1 0 0 -1 0 112.5)">
      <stop offset="0.01" style="stop-color:#4D4D4D" />
      <stop offset="0.51" style="stop-color:#F5F5F5" />
      <stop offset="1" style="stop-color:#4D4D4D" />
    </linearGradient>
    <path fill="url(#SVGID_4_)" stroke="#4C4C4C" stroke-width="0.25" d="M6.869,6.645h23.423" />
  </g>
</svg>

<button type="button" onclick="test()">Click Me!</button>

【问题讨论】:

  • 请向我们展示您到目前为止所做的尝试。
  • 嗯,目前还没有,因为我不知道如何才能接近我想做的事情。

标签: javascript jquery css svg colors


【解决方案1】:

你可以使用each()和css()函数,另外请注意jQuery中的颜色值是以RGB格式返回的,对于#4D4D4D是rgb(77, 77, 77),所以你可以使用这个函数:

jQuery('svg stop').each( function() {
        var color = jQuery(this).css('stop-color');
      if ( color === 'rgb(77, 77, 77)') {
        jQuery(this).css('stop-color', '#ff0000');
      }
  });

你可以在测试链接里试试,我已经为你更新了:https://jsfiddle.net/HebaF/7jvzb34L/8/

【讨论】:

  • 它有效。谢谢!使用 jQuery('svg stop').each( function() 您正在搜索整个 SVG 中的所有 标签,对吧?
  • 随时欢迎您!是的,没错 :) 此外,代码只获取和替换 stop-color 的值。
  • 还有一个问题。如果我在该 SVG 中有两组,并且只想为一组更改停止颜色,我该如何区分它们?
  • 你可以给svg元素添加id或者class属性来区分svg元素。
  • 所以我可以根据组的 id 应用您提供的代码?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 1970-01-01
  • 2021-03-28
  • 1970-01-01
  • 1970-01-01
  • 2012-12-06
  • 2019-04-21
相关资源
最近更新 更多