简体   繁体   English

类型“ HTMLElement”上不存在属性“ width”

[英]Property 'width' does not exist on type 'HTMLElement'

The following TypeScript fails to compile: 以下TypeScript编译失败:

let svg = document.createElement("svg");
svg.width = 300;

Due to the error Property 'width' does not exist on type 'HTMLElement' . 由于错误, Property 'width' does not exist on type 'HTMLElement' But if I change svg to canvas , for example, then it does compile, so it's something about SVGs specifically it seems... 但是,例如,如果我将svg更改为canvas ,那么它确实可以编译,因此特别是关于svg的东西……

Any ideas? 有任何想法吗?

let svg = document.createElement("svg"); doesn't create svg element, but custom html element. 不会创建svg元素,而是创建自定义html元素。

Proper way to create svg element: 创建svg元素的正确方法:

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

 const customSvg = document.createElement("svg") const properSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg") console.log(customSvg instanceof SVGSVGElement) // false console.log(properSvg instanceof SVGSVGElement) // true console.log(customSvg.width) // undefined console.log(properSvg.width) // SVGAnimatedLength {} 

As Marzelin explained , the proper way to create an svg element is by using document.createElementNS instead: 正如Marzelin解释的那样 ,创建svg元素的正确方法是使用document.createElementNS代替:

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

The TypeScript standard lib knows this well, hence why you are getting a HTMLElement return type inference from document.createElement("svg") instead of SVGSVGElement . TypeScript标准库很清楚这一点,因此为什么要从document.createElement("svg")而不是SVGSVGElement获得HTMLElement返回类型推断。

In SVG width and height of elements are attributes and not CSS properties so you'd need to write 在SVG中,元素的宽度和高度是属性,而不是CSS属性,因此您需要编写

 document.getElementById('cercle1').setAttribute("height", "10px"); 

similarly for the width. 宽度也一样。

Change height/width of object SVG javascript 更改对象SVG JavaScript的高度/宽度

In your case: 在您的情况下:

svg.setAttribute("width", "300px");

Your question title is question "Property 'width' does not exist on type 'HTMLElement'" 您的问题标题是问题“类型'HTMLElement'上不存在属性'width'”

HTMLElement has no property width it has property style . HTMLElement没有属性width它具有属性style and style had width stylewidth

let svg = document.createElement("svg");
svg.style.width = '30px';

In your case you need an SVGSVGElement 在您的情况下,您需要一个SVGSVGElement

var svgEl = document.createElementNS("http://www.w3.org/2000/svg", "svg")
svgEl.width = 300

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM