我正在尝试获取 SVG 的宽度。
svg.getBBox().width()
--> 40. 求圆的宽度不考虑描边。svg.width
--> 复杂对象,我在其中找到包含属性值的属性 animVal 和 baseVal:300svg.width.animVal.value
--> 300。我得到了我想要的东西,虽然有时是 0。
有没有办法在结果方面更有效、更可靠地获得 SVG 的大小?
因为,那么我有以下几点:我通过样式更改SVG的大小,但是svg.width.animVal.value
“没有时间”更新。有时它会成功。在以小延迟(10 毫秒)调用代码后,一切都很好。
let svg = document.getElementById('_svg');
console.log(`BBox.width: ${svg.getBBox().width}`);
console.log(`SVG.width: ${svg.width}`); // Получаю сложный объект
printWidth();
svg.style.width = '600px';
svg.style.height = '200px';
printWidth();
setTimeout(printWidth, 10);
function printWidth(){
console.log(`SVG.width.animVal.value: ${svg.width.animVal.value}`);
console.log(`SVG.width.baseVal.value: ${svg.width.baseVal.value}`);
}
<svg fill="yellow" stroke="black" id="_svg">
<circle cx="25" cy="25" r="20"/>
</svg>
链接到原始来源
是的。
animVal
- 在动画期间 - 包含属性的当前值。可能您在这些时刻的代码是在圆圈有时间显示之前执行的。您可以使用
getBoundingClientRect()
:选项 #1:使用
getBBox()
. 它报告宽度和高度,偏移量x
和y
像素,而不考虑元素的缩放 - 也就是说,getBBox()
它接收初始尺寸:选项 #2:使用
getBoundingClientRect()
- 它考虑了使用比例等进行的转换: