簡體   English   中英

嘗試在以編程方式添加的元素上使用getBoundingClientRect()返回寬度和高度0

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

我正在嘗試獲取剛添加到bodyobject元素的getBoundingClientRect() ,但它返回的widthheight為0。目前,我已修復了將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。 我能怎么做?

我的有根據的猜測是,瀏覽器尚不知道圖像的大小,因為您沒有等待圖像完全加載。 我會做這樣的事情:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM