javascript - 如何访问 <svg :use> tag from javascript? 的子项

标签 javascript xhtml svg

我在 XHTML 页面中有以下 SVG 代码

<svg:svg>
<svg:svg width="450" heigth="450" viewBox="0 0 500 500">  
    <svg:defs>
        <svg:g id='mygroup'>
            <svg:circle id='a' cx="15" cy="15" r='15' fill="green" fill-opacity="0.3"/>
            <svg:line id='b' x1="15" y1="15" x2="15" y2="0" style="stroke: black;" />
        </svg:g>
</svg:defs>

<svg:rect width="400" height="400" fill="white" stroke="black" />
<svg:use id="g1" xlink:href="#mygroup" x="100" y="100" onclick="moveMe()" />
<svg:use id="g2" xlink:href="#mygroup" x="100" y="200" />
</svg:svg>

我想用下面的javascript代码修改它

<script><![CDATA[
    function moveMe(){
    obj = document.getElementById("g1");
    obj.setAttributeNS(null, "x", "200"); //Ok it works

    //How can I change the color of the a circle in g1? 
    obj = document.getElementById("g1.a");
    obj.setAttributeNS(null, "fill", "red"); //It doesn't work
    }
 ]]></script>

如何更改“g1”中“a”圆圈的颜色?如何从我的 JavaScript 代码访问它?

编辑:如果我有第二个名为 g2 的 mygroup 项目,我不想更改它的颜色。

最佳答案

一个简单的解决方案是使用“currentColor”关键字传递颜色,如下所示:

<svg:svg>
<svg:svg width="450" heigth="450" viewBox="0 0 500 500">  
<svg:defs>
    <svg:g id='mygroup'>
        <svg:circle id='a' cx="15" cy="15" r='15' fill="currentColor" fill-opacity="0.3"/>
        <svg:line id='b' x1="15" y1="15" x2="15" y2="0" style="stroke: black;" />
    </svg:g>
</svg:defs>

<svg:rect width="400" height="400" fill="white" stroke="black" />
<svg:use id="g1" xlink:href="#mygroup" x="100" y="100" onclick="moveMe()" color="green"/>
<svg:use id="g2" xlink:href="#mygroup" x="100" y="200" color="blue"/>
</svg:svg>

如果您想更改颜色,现在只需更改“use”元素上的“color”属性即可。或者简单地使用 CSS 来实现,例如:

<style>
#g1:hover { color: lime }
</style>

关于javascript - 如何访问 <svg :use> tag from javascript? 的子项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1529886/

相关文章:

css - 我可以先在像素中进行设计,然后再将所有内容转换为 em 吗?

html - CSS:流体边栏 - 流体内容

javascript - Interactjs 与 SVG

javascript - 如何将 ID 和字段值分配给隐藏字段

javascript - jquery中转不透明动画冲突?

jquery - 如何在这个 jquery 代码中制作一个用于打开和关闭 div 的按钮?

wpf - XAML SVG 在运行时颜色变化

javascript - 根据变量重叠 svg 路径事件

javascript - 无法在 Visual Studio 中注释 JavaScript

javascript - 如何在Javascript/HTML/CSS上应用多个转换原点?