JavaScript 中动态创建 SVG 链接

5
我正在使用JavaScript动态创建SVG元素。 对于像矩形这样的可视对象,它可以正常工作,但我在生成功能xlink时遇到了问题。 在下面的示例中,第一个矩形(静态定义)在单击时可以正确工作,但另外两个(在JavaScript中创建)忽略了单击...即使在Chrome中检查元素似乎显示相同的结构。
我看到过多个类似的问题,但没有一个完全解决这个问题。 我找到的最接近的是[adding image namespace in svg through JS still doesn't show me the picture] ,但它不起作用(如下所述)。 我的目标是纯粹使用JavaScript完成此操作,而不依赖于JQuery或其他库。
<!-- Static - this rectangle draws and responds to click -->
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="svgTag">
    <a xlink:href="page2.html" id="buttonTemplate">
        <rect x="20" y="20" width="200" height="50" fill="red" class="linkRect"/>
    </a>
</svg>

<script>
    var svgElement = document.getElementById ("svgTag");

    // Dynamic attempt #1 - draws but doesn't respond to clicks
    var link = document.createElementNS("http://www.w3.org/2000/svg", "a");  // using http://www.w3.org/1999/xlink for NS prevents drawing
    link.setAttribute ("xlink:href", "page2.html");  // no improvement with setAttributeNS
    svgElement.appendChild(link);

    var box = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    box.setAttribute("x", 30); 
    box.setAttribute("y", 30);
    box.setAttribute("width", 200);
    box.setAttribute("height", 50);
    box.setAttribute("fill", "blue");
    link.appendChild(box);

    // Dynamic attempt #2 (also draws & doesn't respond) - per https://dev59.com/R1nUa4cB1Zd3GeqPd8ty
    box = document.createElementNS("http://www.w3.org/2000/svg", "rect");
    box.setAttribute("x", 40); 
    box.setAttribute("y", 40);
    box.setAttribute("width", 200);
    box.setAttribute("height", 50);
    box.setAttribute("fill", "green");
    box.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', "page2.html");
    svgElement.appendChild(box);


根据链接中的评论,我也尝试了使用setAttributeNS。不过看起来问题是我使用了错误的命名空间(svg而不是xlink)。 - user2837568
1个回答

9

只有<a>标签才能成为链接,因此在<rect>元素中添加xlink:href属性将没有任何效果。

你需要使用setAttributeNS方法,你说这种方法不起作用,但对我来说它是有效的,所以可能存在其他问题。

以下示例代码对我来说是可行的:

var svgElement = document.getElementById ("svgTag");

var link = document.createElementNS("http://www.w3.org/2000/svg", "a");
link.setAttributeNS('http://www.w3.org/1999/xlink', 'xlink:href', "page2.html");
svgElement.appendChild(link);

var box = document.createElementNS("http://www.w3.org/2000/svg", "rect");
box.setAttribute("x", 30); 
box.setAttribute("y", 30);
box.setAttribute("width", 200);
box.setAttribute("height", 50);
box.setAttribute("fill", "blue");
link.appendChild(box);
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" id="svgTag">
</svg>


1
谢谢,这确实解决了问题。看起来问题在于我之前尝试使用createElementNS时使用了错误的命名空间:http://www.w3.org/2000/svg而不是http://www.w3.org/2000/svg。我的(错误)想法是"a"元素是sag命名空间的一部分,但现在我看到命名空间应该在属性级别(xlink)确定。 - user2837568

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接