如何使用javascript找到div顶部中心的坐标?

我有一个如下所示的 div,

http://img3.mukewang.com/61d7a83f0001d3dc17410842.jpg

鉴于我使用 getBoundingClientRect() 方法具有顶部、左侧、底部、右侧、x、y 值,我如何获得该 div 的图像中的 (x1,y1) 和 (x2, y2) 坐标。


我尝试过类似下面的方法,


for x1, y1

    return {x: (rect.left + rect.width / 2), y: rect.top + (rect.height / 2)};


for  x2, y2

    return {x: rect.right, y:rect.top + (rect.height / 2)};

有人可以帮我解决这个问题。谢谢。


翻过高山走不出你
浏览 271回答 1
1回答

蛊毒传说

你可以这样做:const circle1 = document.querySelector('#c1');const circle2 = document.querySelector('#c2');const box = document.querySelector('.box');const rect = box.getBoundingClientRect();const topCenter = {&nbsp; x: rect.x + rect.width/2,&nbsp; y: rect.y,}const centerRight = {&nbsp; x: rect.x + rect.width,&nbsp; y: rect.y + rect.height/2,}const circleRadius = 5;circle1.style.left = `${topCenter.x - circleRadius}px`;circle1.style.top = `${topCenter.y - circleRadius}px`;circle2.style.left = `${centerRight.x - circleRadius}px`;circle2.style.top = `${centerRight.y - circleRadius}px`;* {&nbsp; padding: 0;&nbsp; margin: 0;}body {&nbsp; position: relative;&nbsp; width: 100vw;&nbsp; height: 100vh;}.box {&nbsp; --height: 100px;&nbsp; --width: 200px;&nbsp; position: absolute;&nbsp; left: calc((100% - var(--width)) / 2);&nbsp; top: calc((100% - var(--height)) / 2);&nbsp; width: var(--width);&nbsp; height: var(--height);&nbsp; border: 1px solid black;}.circle {&nbsp; position: absolute;&nbsp; border-radius: 50%;&nbsp; background: red;&nbsp; width: 10px;&nbsp; height: 10px;}<div class="circle" id="c1"></div><div class="circle" id="c2"></div><div class="box"></div>
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript