简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM