简体   繁体   中英

How can I set a viewBox on an SVG element created with JavaScript?

When I use a setAttribute('viewBox') on an SVG element that already exists in the DOM, it gets set properly (with an uppercase 'b').

When I create an SVG element in JavaScript and add the 'viewBox' attribute there . . . it ends up in the DOM in all lowercase letters.

Why is this?

 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> 

You have to use document.createElementNS("http://www.w3.org/2000/svg", "svg") instead of 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> 

You're not creating a valid SVG element in the first place though. You can't use createElement to create SVG elements (that's only for HTML elements). You must use createElementNS and provide the SVG namespace as the first argument.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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