我想計算給定兩個指向角的DOM元素之間的距離。我使用 Math.hypot 函式進行計算,但是在計算時出現了錯誤,它略微溢位了角落而不是確切的點。
function getPositionAtCenter(element) {
const {top, left, width, height} = element.getBoundingClientRect();
return {
x: left width / 2,
y: top height / 2
};
}
function getDistanceBetweenElements(a, b) {
const aPosition = getPositionAtCenter(a);
const bPosition = getPositionAtCenter(b);
return Math.hypot(aPosition.x - bPosition.x, aPosition.y - bPosition.y);
}

uj5u.com熱心網友回復:
只需從first的left值中減去 seconddiv的值。leftdiv
let divs = document.querySelectorAll(".div")
let div1Position = divs[0].getBoundingClientRect();
let div2Position = divs[1].getBoundingClientRect();
console.log(div2Position.left - div1Position.left)
<div class="div" style="width:100px; height:100px; background-color:grey; position:absolute; left: 100px; top:0;"></div>
<div class="div" style="width:100px; height:100px; background-color:grey; position:absolute; left:500px; top:0;"></div>
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515351.html
