[英]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
和
style
有width
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.