2017-08-05 120 views
1

我有一个内嵌SVG像如何使用JavaScript修改内联SVG?

<svg> 
    <g id="1" transform="<list of transformations>"> 
     <path d=""> 
     <circle cx="" ...> 
    </g> 
    ... 
</svg> 

与许多团体,我想他们使用JavaScript/jQuery的移动。 我走在网站上输入从值(如旋转),并试图用

$("#1").attr("transform", "<list of new transformations>"); 

,但它不工作。当它从JS文件中执行时,您看不到任何更改。当我在控制台中手动插入时,我可以使用$("#1").attr("transform")检索值,但不会导致可见的更改,也不会更改检查器中的元素。经过Firefox/Chrome测试。

如何在运行时使用javascript或jQuery更改svg?

编辑:问题是,所有的id都出现在脚本的另一部分,所以错误的被选中。

+0

什么是 “<新的转换列表>”? – Slai

+0

类似于“旋转(90,1180,522)translate(1110,452)scale(1.4)” – BlobbyBob

+0

我没有看到任何问题,并且似乎在我尝试时会出现问题,所以问题必须在其他位置。如果没有显示问题的[MCVE](https://stackoverflow.com/help/mcve),我认为你不能得到任何有用的答案。 – Slai

回答

1

总的来说,你的方法似乎是正确的。但是,下面的代码演示了如何做到这一点,所以也许这会告诉你一些细微的错误。

您可以使用jQuery或vanilla JavaScript修改SVG元素,如下面的代码所示,即使用带有jQuery的.attr(attributeName, attributeValue)或使用vanilla JavaScript的.setAttribute(attributeName, attributeValue)

要更改转换,您必须遵循适当的语法(例如讨论here)。

$('#b2').attr('fill', 'red'); 
 
document.querySelector('#c2').setAttribute('fill', 'magenta'); 
 

 
$('#b2').attr('transform', 'translate(0, 20)'); 
 
document.querySelector('#c2').setAttribute('transform', 'rotate(10, 250, 80)');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<p>Top row: three identical yellow rectangles.</p> 
 
<p>Bottom row: three similar rectangles. The second is modified using jQuery, the third using vanilla JavaScript</p> 
 
<svg> 
 
    <rect id="a1" x="50" y="20" width="40" height="20" fill="yellow" /> 
 
    <rect id="b1" x="150" y="20" width="40" height="20" fill="yellow" /> 
 
    <rect id="c1" x="250" y="20" width="40" height="20" fill="yellow" /> 
 

 
    <rect id="a2" x="50" y="70" width="40" height="20" fill="yellow" /> 
 
    <rect id="b2" x="150" y="70" width="40" height="20" fill="yellow" /> 
 
    <rect id="c2" x="250" y="70" width="40" height="20" fill="yellow" /> 
 
</svg>