皈依舞
2022-09-02 21:02:33
我有以下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
提交
取消