[英]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>
提前感謝您的幫助
我們所知道的:元素的Height
、 width
和角度θ
因為元素有動畫或元素被轉換(旋轉)
我們不知道或需要找到的:旋轉后元素的新width
和height
答案在於數學
如果我們知道直角三角形的角和邊(在這種情況下為高度,寬度),那么我們也可以找到其他邊。
要求解具有一側的三角形,您還需要一個非直角。 如果沒有,那是不可能的:
僅給出單個角度,但使用角度公式和關系找到其他角度。
現在正如問題所問:如何獲得藍點的位置而不是我們必須將其添加到left
值
Height*Sinθ + Width*Cosθ
最終代碼變為:
box2.getBoundingClientRect().left + Height*Sinθ + Width*Cosθ
如果從邊框邊緣需要,您也必須包含邊框(如果有高度和寬度)
正如A Haworth指出的旋轉可以從任何點開始,所以沒有檢查每個位置的兼容性,但到目前為止它與元素內的旋轉兼容。 所以請謹慎使用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.