How to get actual (not original) height of a CSS-rotated element

☆樱花仙子☆ 提交于 2019-12-03 07:30:42

问题


I need to obtain actual height of several different elements (for the sake of precise custom tooltip positioning), and some of these elements (not all) are rotated. $(elem).outerHeight() returns the original height, instead of the actual displayed height.

Here's the fiddle with a very simple example: http://jsfiddle.net/NPC42/nhJHE/

I see a possible solution in this answer: https://stackoverflow.com/a/8446228/253974, but am still hoping there is a simpler way.


回答1:


Dusting off my high school geometry and my formidable graphics skills, I put this diagram together. If you have variables width, height, and rotation in javascript, you could express the height this way:

var rotated_height = width * Math.sin(rotation) + height * Math.cos(rotation);




回答2:


If you're only going to be using rotations of 45 degrees and the width and height are always equal, you can calculate the actual rotated height by using the relatively simple mathematical Hypotenuse formula:

which states that the square of the length of the hypotenuse equals the sum of the squares of the lengths of the other two sides.

In this case, the longest side would be the diagonal from corner to opposing corner. This will roughly translate into jQuery like so:

Math.sqrt(Math.pow($('#diamond').height(), 2) + Math.pow($('#diamond').width(), 2))

See the updated jsFiddle.



来源:https://stackoverflow.com/questions/9791403/how-to-get-actual-not-original-height-of-a-css-rotated-element

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!