我有一个内联 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 都出现在脚本的另一部分,所以选择了错误的 id。
最佳答案
总的来说,您的方法似乎是正确的。但是,下面的代码演示了如何做到这一点,所以也许这会告诉您您正在犯的一些细微错误。
您可以使用 jQuery 或 vanilla JavaScript 修改 SVG 元素,如下面的代码所示,即使用 .attr(attributeName, attributeValue)
和 jQuery,或 .setAttribute(attributeName, attributeValue )
用于原生 JavaScript。
要更改转换,您必须遵循适当的语法(例如讨论过的 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>
关于javascript - 如何使用 JavaScript 修改内联 SVG?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45525820/