[英]Trying to use getBoundingClientRect() on an element added programmatically returns width and height 0
I'm trying to get the getBoundingClientRect()
of an object
element that I just added to the body
, but it returns width
and height
0. Currently I fixed the issue adding an SVG to the html containing the same picture and set the visibility to hidden, then getting the width and height from that. 我正在尝试获取刚添加到
body
的object
元素的getBoundingClientRect()
,但它返回的width
和height
为0。目前,我已修复了将SVG添加到包含相同图片的html并将可见性设置为的问题。隐藏,然后从中获取宽度和高度。 The size of the object is a percentage of the window size so I have no way of knowing it in advance. 对象的大小是窗口大小的百分比,因此我无法提前知道。
let bulletSVG = document.createElement("object");
bulletSVG.setAttribute("class", "bullet");
bulletSVG.setAttribute("type", "image/svg+xml");
bulletSVG.setAttribute("data", "imgs/bullet.svg");
document.body.appendChild(bulletSVG);
console.log(bulletSVG.getBoundingClientRect());
I'd rather not add an SVG to the body just to get the width and height. 我宁愿不只是为了获得宽度和高度而向身体添加SVG。 How can I do?
我能怎么做?
My educated guess is that the browser doesn't know yet the size of the image since you're not waiting for the image to be fully loaded. 我的有根据的猜测是,浏览器尚不知道图像的大小,因为您没有等待图像完全加载。 I would do something like that:
我会做这样的事情:
const load = (obj) =>
new Promise(resolve => obj.onload = resolve);
async function addSVG() {
let bulletSVG = document.createElement("object");
bulletSVG.setAttribute("class", "bullet");
bulletSVG.setAttribute("type", "image/svg+xml");
bulletSVG.setAttribute("data", "imgs/bullet.svg");
document.body.appendChild(bulletSVG);
await load(bulletSVG);
console.log(bulletSVG.getBoundingClientRect());
}
addSVG();
UPDATE If your browser doesn't support promises, and you can't / don't want use transpiler (such as Babel 7); 更新如果您的浏览器不支持Promise,并且您不能/不希望使用转译器(例如Babel 7); you make it working using directly the event handler, although it won't be so elegant:
您可以直接使用事件处理程序来使其工作,尽管它不会那么优雅:
function addSVG() {
let bulletSVG = document.createElement("object");
bulletSVG.setAttribute("class", "bullet");
bulletSVG.setAttribute("type", "image/svg+xml");
bulletSVG.setAttribute("data", "imgs/bullet.svg");
document.body.appendChild(bulletSVG);
bulletSVG.onload = function() {
console.log(bulletSVG.getBoundingClientRect());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.