为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

翻过高山走不出你 2022-01-07 10:40:17
我有一个如下所示的 div,鉴于我使用 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)};有人可以帮我解决这个问题。谢谢。
查看完整描述

1 回答

?
蛊毒传说

TA贡献1895条经验 获得超3个赞

你可以这样做:


const circle1 = document.querySelector('#c1');

const circle2 = document.querySelector('#c2');

const box = document.querySelector('.box');


const rect = box.getBoundingClientRect();


const topCenter = {

  x: rect.x + rect.width/2,

  y: rect.y,

}

const centerRight = {

  x: rect.x + rect.width,

  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`;

* {

  padding: 0;

  margin: 0;

}

body {

  position: relative;

  width: 100vw;

  height: 100vh;

}

.box {

  --height: 100px;

  --width: 200px;

  position: absolute;

  left: calc((100% - var(--width)) / 2);

  top: calc((100% - var(--height)) / 2);

  width: var(--width);

  height: var(--height);

  border: 1px solid black;

}


.circle {

  position: absolute;

  border-radius: 50%;

  background: red;

  width: 10px;

  height: 10px;

}

<div class="circle" id="c1"></div>

<div class="circle" id="c2"></div>

<div class="box"></div>


查看完整回答
反对 回复 2022-01-07
  • 1 回答
  • 0 关注
  • 270 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号