以下打字稿編譯失敗:住宅「寬度」上類型不存在「的HTMLElement」
let svg = document.createElement("svg");
svg.width = 300;
由於錯誤Property 'width' does not exist on type 'HTMLElement'
。但是,如果我改變svg
爲canvas
,例如,然後它編譯,所以這是關於SVG的東西,具體看起來...
任何想法?
以下打字稿編譯失敗:住宅「寬度」上類型不存在「的HTMLElement」
let svg = document.createElement("svg");
svg.width = 300;
由於錯誤Property 'width' does not exist on type 'HTMLElement'
。但是,如果我改變svg
爲canvas
,例如,然後它編譯,所以這是關於SVG的東西,具體看起來...
任何想法?
你的問題的標題是問題
HTMLElement
「屬性‘寬度’不上鍵入‘HTML元素’存在」沒有財產width
它具有財產style
。和style
有width
let svg = document.createElement("svg");
svg.style.width = '30px';
你的情況,你需要一個SVGSVGElement
var svgEl = document.createElementNS("http://www.w3.org/2000/svg", "svg")
svgEl.width = 300
在SVG寬度和元素的高度屬性,而不是CSS屬性,所以你需要寫
document.getElementById('cercle1').setAttribute("height", "10px");
類似的寬度。
Change height/width of object SVG javascript
你的情況:
svg.setAttribute("width", "300px");
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 {}
如果要設置寬度,您必須使用'properSvg.setAttribute(」width「,」300「) ''或'properSvg.width.baseVal.value =「300」' –
As Marzelin explained,適當的方式來創建一個svg
元件是通過使用document.createElementNS代替:
document.createElementNS("http://www.w3.org/2000/svg", "svg");
打字稿標準庫知道這口井,因此爲什麼你是從document.createElement("svg")
,而不是SVGSVGElement
得到一個HTMLElement
返回類型推斷。
'canvas'是一個特殊的元素。普通元素沒有'width'屬性 – marzelin
svg有寬度屬性https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/width – brk
@brk但這是一個標記屬性,而不是一個對象屬性。或者是一個(如id)這兩個? –