我正在使用JS将SVG元素插入HTML。我希望元素具有for someitem in collection_of_items
和width=100%
。然后,我想在SVG元素中插入一个路径。路径height=200px
取决于SVG元素的大小,但插入后即为0 0。我尝试过:
d
还有这个CSS:
var board = document.createElementNS('http://www.w3.org/2000/svg','svg');
document.body.append(board);
var h = board.height.baseVal.value; //appears to be 0
var w = board.width.baseVal.value; //appears to be 0
无论是否有svg {
width: 100%;
height: 200px;
display: block;
}
,结果都是一样的。难道我做错了什么?当我的元素的高度和宽度非零时,会触发任何事件吗?谢谢!
答案 0 :(得分:0)
<svg>
width
和height
属性的默认值为100%
。
您正在访问的IDL属性将反映出来。
您想要的可能更多是节点的边界矩形,但是在HTML中,如果未明确设置这些属性,则默认值为300 * 150(我不记得确切的原因,这与inline-replacedElements有关IIRC ...,但它也至少涉及
var board = document.createElementNS('http://www.w3.org/2000/svg','svg');
document.body.append(board);
console.log(board.width.baseVal.valueAsString); // "100%"
// what you want is the bounding rect
const rect = board.getBoundingClientRect();
const w = rect.width; // 300 (+2 border)
const h = rect.height; // 150 (+2 border)
console.log(w, h);
svg { border: 1px solid; }
如果要将其默认设置为300 * 150以外的其他值,则必须明确设置以下属性:
var board = document.createElementNS('http://www.w3.org/2000/svg','svg');
board.setAttribute('width', '100%');
board.setAttribute('height', '100%');
document.body.append(board);
console.log(board.width.baseVal.valueAsString); // "100%"
// what you want is the bounding rect
const rect = board.getBoundingClientRect();
const w = rect.width;
const h = rect.height;
console.log(w, h);
svg { border: 1px solid; }