防止SVG CSS出血



因此,我基本上有一个带有两个SVG的网页。单击选定的SVG将是可见的。

问题:如果带有视口的SVG 0 0 20 20 首先加载,并具有2个宽度为2,然后将另一个SVG加载给其他SVG 0 0 2000 2000 2000 ,第一个宽度的宽度已继承为第二个。第二个现在的中风宽度为2,而不是200。

这就是容器的方式:

<div class="clearView-container">
  // svg 2
</div>
<div class="techView-container" style="display: none;">
  // svg 1
</div>

SVG1:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="273.263mm" height="210.784mm" viewBox="-49.35 -56.0421 136.632 105.392">
<defs>
 <style type="text/css">
 .pen_style1 {stroke: #000000;stroke-width: 0.25;}
 .pen_style3 {stroke: #c6c6c6;stroke-width: 0.125;stroke-dasharray: 1, 0.5}
 .pen_style4 {stroke: #ff0000;stroke-width: 0.125;stroke-dasharray: 0.2, 0.5, 1, 0.5}
 .cos {stroke: #0037a0;}
 .hiddenLine {     display: none;   }
 </style>
</defs>

SVG2:

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="127.46mm" height="104.6mm" viewBox="-3214 -2698 6373 5230">
<defs>
 <style type="text/css">
 .pen_style1 {stroke: #000000;stroke-width: 25;}
 .pen_style3 {stroke: #c6c6c6;stroke-width: 12.5;stroke-dasharray: 100, 50}
 .pen_style4 {stroke: #ff0000;stroke-width: 12.5;stroke-dasharray: 20, 50, 100, 50}
 .cos {stroke: #0037a0;}
 .hiddenLine {     display: none;   }
 </style>
</defs>

现在,如果首先加载了此(SVG1(,则clearView-container中的SVG从techView-container获取属性。

是否有一种方法可以防止两个SVG的<defs>"流血"?

如果某人需要答案。这就是我最终这样做的方式。我从服务器作为字符串获得SVG。比我使用@DBSS解决方案与ID(无法执行服务器端,所以这里是:(

function _injectCustomCSS (svg: string): string {
  const newID = 'id' + MathLib.hashCode(svg);
  const replaceStr = /.pen/g;
  const svgDoc = new DOMParser().parseFromString(svg, 'image/svg+xml');
  svgDoc.getElementsByTagName('svg')[0].setAttribute('id', newID);
  svgDoc.getElementsByTagName('style')[0].textContent = svgDoc.getElementsByTagName('style')[0].textContent.replace(replaceStr, '#' + newID + '>.pen');
  /* ... */
  return new XMLSerializer().serializeToString(svgDoc);
};

最新更新