尝试使用原始 JavaScript 注入(inject) SVG 元素。我可以检查并看到元素已加载,但尺寸最终为 0x0,而不是元素上设置的大小。
(function() {
// Constructor
this.Loading = function() {
this.svgNamespace = "http://www.w3.org/2000/svg";
var svg = createSvgObject("svg", "loaderSvg");
svg.setAttributeNS(null, "width", 200);
svg.setAttributeNS(null, "height", 200);
document.getElementById("possibleLoadingLocation").appendChild(svg);
var circle = createSvgObject("circle", "test");
circle.setAttribute("cx", 40);
circle.setAttribute("cy", 40);
circle.setAttribute("r", 30);
circle.setAttribute("stroke", "#000");
circle.setAttribute("stroke-width", 2);
circle.setAttribute("fill", "#f00");
svg.appendChild(circle);
}
function createSvgObject(elementType, elementId) {
if (elementType === undefined || elementType == null) {
throw "elementType is required to createSvgObject";
}
var element = document.createElementNS(this.svgNamespace, elementType);
if (elementId != null) {
element.setAttributeNS(null, "id", elementId);
}
return element
}
}());
var myLoading = new Loading();
SVG 对象和 Circle 对象的尺寸均为 0x0。我在下面的示例中使用了 css 来强制 svg 匹配包含它的 div 的尺寸。我还将检查中的确切 svg 代码复制到正文中,没有 css,在那里我可以看到它的大小正确。
感谢您的帮助。
最佳答案
更改位置
this.svgNamespace = "http://www.w3.org/2000/svg";
到之前:
this.Loading = function() {
关于javascript - 注入(inject)的 SVG 丢失尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41938227/