javascript 无法使用getBoundingClientRect将sum存储到变量

mbskvtky  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(118)

下面是代码:

var finalProductDiv;
var workingsDiv;
var div1x = 0;

setTimeout(function(){ 
   finalProductDiv = document.getElementById('contentContaineriFrame').contentWindow.document.getElementById('finalProduct');
   workingsDiv = document.getElementById('contentContaineriFrame').contentWindow.document.getElementById('workings');
   div1x = finalProductDiv.getBoundingClientRect().left + finalProductDiv.getBoundingClientRect().width/2;
 }, 2000);

问题是div1x总是返回0。
finalProductDiv.getBoundingClientRect().left返回16,finalProductDiv.getBoundingClientRect().width返回690。两个值都是正确的,那么为什么div1x = 0?它应该是353对吗?

zzlelutf

zzlelutf1#

这取决于您将console.log放在哪里以获取div1x的值。
下面演示的区别时,你把内部与外部设置超时。

var finalProductDiv;
var workingsDiv;
var div1x = 0;

setTimeout(() => {
finalProductDiv = document.getElementById('finalProduct');
   workingsDiv = document.getElementById('workings');
   div1x = finalProductDiv.getBoundingClientRect().left + finalProductDiv.getBoundingClientRect().width/2;
   console.log("Value in settimeout : ", div1x)
   // 
   // You should put codes that requires the value of div1x here
   //
   },2000)
   
   // value of div1x here will be 0 because it's not yet calculated
   console.log("Value outside settimeout : ", div1x)
<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <div id="finalProduct" style="width: 320px; background-color: 'red'" />
    <div id="workings" style="width: 600px; background-color: 'blue'" />

  </body>
</html>

相关问题