[英]How can I determine the viewBox of any <svg> Element from JavaScript?
[英]How can I set a viewBox on an SVG element created with JavaScript?
當我在DOM中已經存在的SVG元素上使用setAttribute('viewBox')時,將對其進行正確設置(使用大寫的'b')。
當我在JavaScript中創建SVG元素並在其中添加'viewBox'屬性時。 。 。 它以所有小寫字母結尾在DOM中。
為什么是這樣?
document.querySelector('#circle svg').setAttribute('viewBox', '190 190 20 20'); let svg = document.createElement('svg'), circle = document.createElement('circle'); circle.setAttribute('cx', 200); circle.setAttribute('cy', 200); circle.setAttribute('r', 10); svg.setAttribute('viewBox', '190 190 20 20'); svg.appendChild(circle); document.body.appendChild(svg); // document.querySelector('#circleGenerated svg').setAttribute('viewBox', '190 190 20 20');
svg { border: 2px dashed #666; width: 200px; height: 200px; }
<p>Existing svg with dynamically added viewBox attribute:</p> <div id="circle"> <svg> <circle cx="200" cy="200" r="10" id="center-point" fill="#bbb" /> </svg> </div> <p>Generated svg with dynamically added viewBox attribute:</p>
您必須使用document.createElementNS("http://www.w3.org/2000/svg", "svg")
代替document.createElement('svg')
document.querySelector('#circle svg').setAttribute('viewBox', '190 190 20 20'); let svg = document.createElementNS("http://www.w3.org/2000/svg", "svg"), circle = document.createElementNS("http://www.w3.org/2000/svg", "circle"); circle.setAttribute('cx', 200); circle.setAttribute('cy', 200); circle.setAttribute('r', 10); svg.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:xlink", "http://www.w3.org/1999/xlink"); svg.setAttribute('viewBox', '190 190 20 20'); svg.appendChild(circle); document.body.appendChild(svg); // document.querySelector('#circleGenerated svg').setAttribute('viewBox', '190 190 20 20');
svg { border: 2px dashed #666; width: 200px; height: 200px; }
<p>Existing svg with dynamically added viewBox attribute:</p> <div id="circle"> <svg> <circle cx="200" cy="200" r="10" id="center-point" fill="#bbb" /> </svg> </div> <p>Generated svg with dynamically added viewBox attribute:</p>
首先,您並不是在創建有效的SVG元素。 您不能使用createElement創建SVG元素(僅用於HTML元素)。 您必須使用createElementNS並提供SVG名稱空間作為第一個參數。
let svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg'),
circle = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.