亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何使用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 關注
  • 267 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號