2016-07-16 166 views
0

我认为,当一个用户发送一条消息,包括一个http://这里我的代码会工作,但不会:如何在使用Javascript的SVG文本中添加超链接?

function showMessage(nameStr, contentStr, textColor) { 

    var node = document.getElementById("chatbox"); 
    var nameNode = document.createElementNS("http://www.w3.org/2000/svg", "tspan", textColor); 

    nameNode.setAttribute("x", 100); 
    nameNode.setAttribute("dy", 20); 
    nameNode.setAttribute("fill", textColor); 
    nameNode.appendChild(document.createTextNode(nameStr)); 

    node.appendChild(nameNode); 

    var contentNode = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); 

    contentStr = contentStr.replace(/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g, 
     '<a target="blank" href="$1">$1</a>'); 

    contentNode.setAttribute("x", 200); 
    contentNode.setAttribute("fill", textColor); 
    contentNode.innerHTML = contentStr; 

    // Add the name to the text node 
    node.appendChild(contentNode); 
} 

任何人都可以找到这段代码中的错误?

  • nameStr是发送消息的人的姓名,
  • contentStr是用户输入,并且该程序会自动改变,因此任何链接变成可点击的链接,并
  • textColor只是颜色的消息。
+0

欢迎堆栈溢出。对于你所问的问题,你的代码太复杂了。请阅读:http://stackoverflow.com/help/mcve也许只有一行是相关的。你是否单独测试过它? –

+0

这个正则表达式对网址做了很多错误的假设。 – zzzzBov

+0

我认为代码工作正常时,我检查替换脚本:/ –

回答

1

为了使超链接的svg元素在里面工作,你应该建立XLink命名空间,除了默认的一个svg

<svg width="500" height="500" 
    xmlns="http://www.w3.org/2000/svg" 
    xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1"> 

然后你可以使用xlink:href属性:

<a xlink:href="http://www.example.com">click here</a> 

综合以下片段:

function showMessage(nameStr, contentStr, textColor) { 
 

 
    var node = document.getElementById("chatbox"); 
 
    var nameNode = document.createElementNS("http://www.w3.org/2000/svg", "tspan", textColor); 
 

 
    nameNode.setAttribute("x", 100); 
 
    nameNode.setAttribute("dy", 20); 
 
    nameNode.setAttribute("fill", textColor); 
 
    nameNode.appendChild(document.createTextNode(nameStr)); 
 

 
    node.appendChild(nameNode); 
 

 
    var contentNode = document.createElementNS("http://www.w3.org/2000/svg", "tspan"); 
 

 
    contentStr = contentStr.replace(/((http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?)/g, 
 
     '<a fill="purple" target="blank" xlink:href="$1">$1</a>'); // "xlink:" added! 
 

 
    contentNode.setAttribute("x", 200); 
 
    contentNode.setAttribute("fill", textColor); 
 
    contentNode.innerHTML = contentStr; 
 

 
    // Add the name to the text node 
 
    node.appendChild(contentNode); 
 
} 
 
// Sample call: 
 
showMessage('John Doe', 'click this http://www.example.com', 'blue');
a { 
 
    text-decoration: underline; 
 
}
<svg width="500" height="500" 
 
    xmlns="http://www.w3.org/2000/svg" 
 
    xmlns:xlink="http://www.w3.org/1999/xlink" 
 
    version="1.1"> 
 

 
<text id="chatbox"></text> 
 

 
</svg>

+0

这工作完美!现在,它的工作原理,我将如何能够改变超链接的颜色,并强调它?不能相信我错过了那么多的正确的代码哈哈 –

+0

谢谢! –

相关问题