svg:Wrap<文本>在<a>使用javascript将显示白色页面(没有错误)

svg: Wrap <text> in <a> using javascript results in white page (no error)

本文关键字:gt lt 白色 显示 有错误 使用 文本 Wrap javascript svg      更新时间:2023-09-26

我使用jasondavies的d3云来渲染标签云,它运行良好。但是,我也希望所有项目都是可点击的,最好的解决方案是将所有<text>元素封装在xlink的a元素中。下面是一个简单的例子:

<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<body>
<svg height="60" width="125">
    <g transform="translate(62,30)">
        <text transform="translate(20,8)rotate(0)" text-anchor="middle" style="font-size: 100px; font-family: Impact; fill: rgb(31, 119, 180);">text</text>
    </g>
</svg>
<script>
window.setTimeout(function(){
    var ns = 'http://www.w3.org/1999/xlink';
    document.querySelector('svg').setAttribute('xmlns:xlink', ns);
    var el = document.querySelectorAll('g text').item(0);
    var w = document.createElementNS(ns, 'a');
    w.setAttributeNS(ns, 'xlink:href', '/test/'+ el.textContent);
    w.setAttributeNS(ns, 'target', '_top');
    w.appendChild(el.cloneNode(true));
    el.parentNode.replaceChild(w, el);
}, 1000);
</script>
</body>
</html>

然而,这会导致文本元素变得不可见(在Firefox和Chrome中)。奇怪的是,如果我使用DOM检查器复制生成的SVG,并将其粘贴到一个单独的文件中;它运行良好。

我目前已经通过添加onclick处理程序来解决问题,但这还远远不够完美。

您需要为链接指定SVG命名空间,否则a元素将无法正确解释:

var w = document.createElementNS(d3.ns.prefix.svg, 'a');
// etc