javascript - 仅在 Inspector、SVG 中可见的元素

标签 javascript svg

我尝试使用按钮创建更多圆圈,但不起作用。单击后它们会显示在 Mozilla 检查器中:

inspector 但它们对我来说是不可见的。我在这里看到过类似的问题,但没有一个有效。你能帮我吗? Atm 我不知道该怎么办。

圆.js

class Circle {
constructor(id, posx, posy, r, fill) {
    this.id = id;
    this.posx = posx;
    this.posy = posy;
    this.r = r;
    this.fill = fill;
}}

creator.js

function createCircle() {

let color = ["blue", "black", "red", "green", "purple", "orange", "yellow"]
const circle = new Circle("node", 100, 100, 50, color[0]);

var node = document.createElement("CIRCLE");
node.setAttribute("id", "node");
node.setAttribute("cx", circle.posx);
node.setAttribute("cy", circle.posy);
node.setAttribute("r", circle.r);
node.setAttribute("fill", circle.fill);
document.getElementById("frame").appendChild(node);

console.log(circle.fill);}

正文和来自index.html

<body onload="myFunction()">
<svg id="sss" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
    <svg id="frame" width="1020px" height="820px" viewBox="0 0 1020 820">
        <circle id="circle0" cx="100" cy="100" r="50" fill="black" />
    </svg>
</svg>
<button onclick="createCircle()">Create circle</button></body>

最佳答案

SVG 元素与典型 HTML 元素来自不同的命名空间。 HTML 文档可以混合来自不同 XML 方言的标签,例如 XHTML,它们是标准 HTML 元素,但也可以混合不同的方言,如 SVG 命名空间。为了从正确的命名空间创建正确的元素,您需要使用不同的 JavaScript 方法来指定命名空间:

document.createElementNS(namespace, element);

第一个参数是命名空间,因此您应该使用:“http://www.w3.org/2000/svg ”,第二个参数是元素,在本例中为“circle”。所以尝试一下:

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

如果您更感兴趣,请查看 MDN 文档:

https://developer.mozilla.org/en-US/docs/Web/SVG/Namespaces_Crash_Course

https://developer.mozilla.org/en-US/docs/Web/API/Document/createElementNS

关于javascript - 仅在 Inspector、SVG 中可见的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53235169/

相关文章:

javascript - 单击按钮时 knockout 更改跨度可见状态

python - 工具提示在我的 pygal 条形图中不起作用?

javascript - highcharts 可缩放 6 个月折线图

javascript - 使用 Angular 集 id 访问元素

javascript - createElementNS 是否始终离线工作?特别是 SVG 命名空间

jquery - 动画后如何在 SVG 中保持原始破折号?

css - 绘制图像并用颜色或图案动态填充它

javascript - 将裁剪区域与非裁剪区域分开

javascript - 如何在 sails.js 0.10 中接收套接字事件?

javascript - 为什么 jQuery 不能在 IE11 中运行