尝试在以编程方式添加的元素上使用 getBoundingClientRect() returns 宽度和高度 0

Trying to use getBoundingClientRect() on an element added programmatically returns width and height 0

我正在尝试获取我刚刚添加到 bodyobject 元素的 getBoundingClientRect(),但它 returns width 并且height 0. 目前我解决了向包含相同图片的 html 添加 SVG 并将可见性设置为隐藏,然后从中获取宽度和高度的问题。对象的大小是 window 大小的百分比,所以我无法提前知道它。

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());

我不想为了获得宽度和高度而将 SVG 添加到正文。我该怎么办?

我有根据的猜测是浏览器还不知道图像的大小,因为您没有等待图像完全加载。我会做这样的事情:

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();

更新 如果您的浏览器不支持 promises,并且您不能/不想使用转译器(例如 Babel 7);你直接使用事件处理程序让它工作,虽然它不会那么优雅:

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());
  }
}