使用 HTML 中的 javascript 动态创建 SVG 元素 [英] Creating SVG elements dynamically with javascript inside HTML
本文介绍了使用 HTML 中的 javascript 动态创建 SVG 元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想在 HTML 页面内创建一个矩形,然后在该矩形上写一些文本.我还需要将该文本作为超链接.这就是我所做的,但它不起作用:
I want to create a rectangle inside an HTML page, then write some text on that rectangle. I also need that text to be a hyperlink. This is what I did but it is not working:
<!DOCTYPE html>
<html>
<body>
<script>
var svg = document.documentElement;
var svgNS = svg.namespaceURI;
var rect = document.createElementNS(svgNS,'rect');
rect.setAttribute('x',5);
rect.setAttribute('y',5);
rect.setAttribute('width',500);
rect.setAttribute('height',500);
rect.setAttribute('fill','#95B3D7');
svg.appendChild(rect);
document.body.appendChild(svg);
var h=document.createElement('a');
var t=document.createTextNode('Hello World');
h.appendChild(t);
document.body.appendChild(h);
</script>
</body>
</html>
你能帮忙吗?谢谢.
推荐答案
更改
var svg = document.documentElement;
到
var svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
这样你就可以创建一个 SVG
元素.
so that you create a SVG
element.
要使链接成为超链接,只需添加一个 href
属性:
For the link to be an hyperlink, simply add a href
attribute :
h.setAttributeNS(null, 'href', 'http://www.google.com');
这篇关于使用 HTML 中的 javascript 动态创建 SVG 元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文