在按钮单击时查找并替换颜色 jQuery.



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

有没有办法在整个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>

您可以使用 each(( 和 css(( 函数,另外请注意,jQuery 中的颜色值以 RGB 格式返回,即 rgb(77, 77, 77( 表示 #4D4D4D,因此您可以使用此函数:

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/

最新更新