簡體   English   中英

旋轉時如何獲取元素的高度和寬度

[英]How to get height and width of element when it is rotated

因為我可以使用e.getBoundingClientRect().left從屏幕左側獲取元素的位置

當我們想要獲取端點的位置時,根據需要添加寬度或高度,但是如何在元素旋轉時獲取端點的位置。

是否可以獲取值

在此處輸入圖片說明

 let getBoxPos = document.querySelectorAll(".demo") let box1 = document.querySelector("#box1") let box2 = document.querySelector("#box2") let box3 = document.querySelector("#box3") let s = ""; function func() { getBoxPos.forEach(e => { let figXValue = e.getBoundingClientRect().left; s = Number(s) + Number(1); console.log("Start distance for box" + s + ":" + figXValue) }) console.log("End distance for box1:" + (box1.getBoundingClientRect().left + 24)); console.log("End distance for box3:" + (box3.getBoundingClientRect().left + 104)); console.log("Don't know the correct way for box2:Is it box2.getBoundingClientRect().left + 100 or box2.getBoundingClientRect().left + 20 or none of them "); } func();
 .demo { height: 100px; width: 20px; margin-left: 40px; border: 2px solid black; } .demo:nth-child(2) { border: 2px solid red; transform: rotate(-45deg); } .demo:nth-child(3) { border: 2px solid green; transform: rotate(-90deg); }
 <div class="demo" id="box1"></div> <div class="demo" id="box2"></div> <div class="demo" id="box3"></div>

提前感謝您的幫助

我們所知道的:元素的Heightwidth和角度θ因為元素有動畫或元素被轉換(旋轉)

我們不知道或需要找到的:旋轉后元素的新widthheight

答案在於數學

如果我們知道直角三角形的角和邊(在這種情況下為高度,寬度),那么我們也可以找到其他邊。

要求解具有一側的三角形,您還需要一個非直角。 如果沒有,那是不可能的:

  1. 如果您有斜邊,請將其乘以 sin(θ) 以獲得與角度相反的邊的長度。
  2. 或者,將斜邊乘以 cos(θ) 以獲得與角度相鄰的邊。
  3. 如果非斜邊與角相鄰,則將其除以 cos(θ) 即可得到斜邊的長度。
  4. 或者,將此長度乘以 tan(θ) 以獲得與角度相反的邊的長度。
  5. 如果你有一個角和它的對邊,你可以用sin(θ)除以邊長得到斜邊。
  6. 或者,將長度除以 tan(θ) 以獲得與角度相鄰的邊的長度。

取自 OMNI 計算器

在此處輸入圖片說明

僅給出單個角度,但使用角度公式和關系找到其他角度。

現在正如問題所問:如何獲得藍點的位置而不是我們必須將其添加到left

Height*Sinθ + Width*Cosθ

最終代碼變為:

box2.getBoundingClientRect().left + Height*Sinθ + Width*Cosθ

如果從邊框邊緣需要,您也必須包含邊框(如果有高度和寬度)

正如A Haworth指出的旋轉可以從任何點開始,所以沒有檢查每個位置的兼容性,但到目前為止它與元素內的旋轉兼容。 所以請謹慎使用

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM