我有以下Node类,我用它来创建自定义元素。node-elementclass Node extends SVGCircleElement{ static get observedAttributes() { return ["coordinates"]; } constructor() { super(); this.attributeMap = {coordinates:(coordinates)=>this.updateCoordinates(coordinates)} } connectedCallback(){ this.initNode(); } updateCoordinates(coordinates) { this.setAttribute("cx",`${coordinates.x}`); this.setAttribute("cy",`${coordinates.y}`); this.setAttribute("r",50); } initNode() { this.className="node"; } attributeChangedCallback(name,oldValue,newValue) { if(oldValue!==newValue) { this.attributeMap[name](JSON.parse(newValue)) } }}我注册此元素使用:-customElements.define('node-element',Node);我正在创建此元素,如下所示:-let newNode = document.createElement("node-element");这就是我得到以下错误的地方:-Uncaught TypeError: Illegal constructor at new Node (index.js:9) at SVGSVGElement.drawNode (index.js:43)第 43 行对应于 createElement 代码。
1 回答

慕勒3428872
TA贡献1848条经验 获得超6个赞
很想被证明是错误的,只是在SVG项目上花了2个月
AFAIK,你不能扩展SVG元素
只能在 HTML 命名空间中创建自定义元素http://www.w3.org/1999/xhtml
SVG 元素位于 SVG 命名空间中http://www.w3.org/2000/svg
从文档: https://html.spec.whatwg.org/multipage/custom-elements.html#element-definition
如果扩展的元素接口和 HTML 命名空间是 HTMLUnknownElement,
则抛出一个“NotSupportedError”DOMException。
和
如果命名空间不是 HTML 命名空间,则返回 null
正在进行的关于允许其他命名空间的 W3C 讨论如下:https://github.com/w3c/webcomponents/issues/634
HTML 命名空间也有限制
Apple/Safari实现了Autonomous Custom Elements(从HTMLElement扩展而来)
但拒绝实现自定义内置元素(从 HTML 命名空间扩展任何内置元素)
如果要生成 SVG,则必须扩展并生成整个 SVG 标记:HTMLElement
<svg xmlns='http://www.w3.org/2000/svg' viewBox='V'><circle cx='X' cy='Y' r='R'/></svg>
添加回答
举报
0/150
提交
取消