代码如下:
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,对吧?
这取决于您将console.log放在何处以获取div1x的值。
下面演示了当你把settimeout放在里面和外面时的区别。
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>