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

时间:2019-02-18 15:15:19

标签: javascript svg getboundingclientrect

我正在尝试获取刚刚添加到getBoundingClientRect()的{​​{1}}元素的object,但是它返回bodywidth 0目前,我已修复了将SVG添加到包含相同图片的html并将可见性设置为隐藏,然后从中获取宽度和高度的问题。对象的大小是窗口大小的百分比,所以我无法提前知道它。

height

我不想只是为了获得宽度和高度而在身体上添加SVG。我该怎么办?

1 个答案:

答案 0 :(得分:2)

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

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

更新 如果您的浏览器不支持promise,并且您不能/不希望使用转译器(例如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());
  }
}