1

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

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 只是为了获得宽度和高度。我能怎么做?

4

1 回答 1

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

更新 如果您的浏览器不支持承诺,并且您不能/不想使用转译器(例如 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());
  }
}
于 2019-02-18T15:31:06.847 回答