【问题标题】:How to get height and width of element when it is rotated [duplicate]旋转时如何获取元素的高度和宽度[重复]
【发布时间】:2021-11-14 13:28:44
【问题描述】:

因为我可以使用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>

【问题讨论】:

  • 你知道它是围绕中心点旋转还是在其他地方?
  • @AHaworth 我使用了transform-origin: top center;,所以它来自中心顶部,但值保持不变。如果您能提供任何不同或更好的解决方案,我将不胜感激

标签: javascript html css


【解决方案1】:

我们知道的:元素的Heightwidth和角度θ,因为元素有动画或者元素被变换(旋转)

我们不知道或需要查找的内容:旋转后元素的新widthheight

如果我们知道直角三角形的角度和边(在这种情况下是高度,宽度),那么我们也可以找到其他边。

要求解具有一侧的三角形,还需要其中一个非直角。如果没有,那是不可能的:

  1. 如果有斜边,乘以 sin(θ) 得到长度 与角相对的一侧。
  2. 或者,将斜边乘以 cos(θ) 得到边 与角度相邻。
  3. 如果非斜边与角相邻,则将其分割 通过 cos(θ) 得到斜边的长度。
  4. 或者,将此长度乘以 tan(θ) 以获得 与角相对的一侧。
  5. 如果你有一个角和它的对面,你可以把 通过 sin(θ) 得到斜边的边长。
  6. 或者,将长度除以 tan(θ) 得到 与角相邻的一侧。

Taken from OMNI Calculator

仅给出单个角度,但使用角度公式和关系找到其他角度。

现在问题问:如何获得蓝点的位置而不是我们必须将其添加到 left

Height*Sinθ + Width*Cosθ

最终代码变成:

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

如果需要从边框边缘开始,您也必须在高度和宽度上包含边框

正如A Haworth 指出的旋转可以从任何点开始,因此检查了不同位置的兼容性,并且到目前为止似乎与任何点的旋转兼容。 >>元素从任意位置旋转一个角度。

This answer may help further

【讨论】:

  • 上面的transform-origin是什么?
  • transform-origin: top center;@AHaworth
  • @AHaworth 更新了答案以解决您指出的问题。你能告诉我这是正确还是错误的方法或建议任何方法
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
  • 2018-09-08
  • 1970-01-01
  • 1970-01-01
  • 2021-10-06
  • 2015-09-21
  • 1970-01-01
相关资源
最近更新 更多