2017-07-28 21 views
2

以下打字稿編譯失敗:住宅「寬度」上類型不存在「的HTMLElement」

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

由於錯誤Property 'width' does not exist on type 'HTMLElement'。但是,如果我改變svgcanvas,例如,然後它編譯,所以這是關於SVG的東西,具體看起來...

任何想法?

+1

'canvas'是一個特殊的元素。普通元素沒有'width'屬性 – marzelin

+0

svg有寬度屬性https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/width – brk

+0

@brk但這是一個標記屬性,而不是一個對象屬性。或者是一個(如id)這兩個? –

回答

-2

你的問題的標題是問題

HTMLElement「屬性‘寬度’不上鍵入‘HTML元素’存在」沒有財產width它具有財產style。和stylewidth

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

你的情況,你需要一個SVGSVGElement

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

此代碼確實創建了一個自定義元素(或標記{svg}),但它並不意味着{ SVGSVGElement}。 – Luillyfe

+1

是的,我錯過了。我專注於問題標題「屬性寬度」在'HTMLElement'類型上不存在'「 – qiAlex

0

在SVG寬度和元素的高度屬性,而不是CSS屬性,所以你需要寫

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

類似的寬度。

Change height/width of object SVG javascript

你的情況:

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

let svg = document.createElement("svg");不創建SVG元素,但自定義HTML元素。

適當的方式來創建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 {}

+0

如果要設置寬度,您必須使用'properSvg.setAttribute(」width「,」300「) ''或'properSvg.width.baseVal.value =「300」' –

1

As Marzelin explained,適當的方式來創建一個svg元件是通過使用document.createElementNS代替:

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

打字稿標準庫知道這口井,因此爲什麼你是從document.createElement("svg"),而不是SVGSVGElement得到一個HTMLElement返回類型推斷。

相關問題