0

我有一个使用 -webkit-transform:rotate(45deg) 旋转的 div 元素。如果我尝试像这样在旋转后访问它的当前位置

var x = $('#tap-area').offset().left;
var y = $('#tap-area').offset().top;

它返回给我的不是原始左上角的实际值,而是整个 div 边界框的左上角在哪里(在 DIV 之外物理上最远的左上角)。

旋转后如何计算/获取div的原始左上角

例如:如果我将它旋转 90 度,我现在想要得到的值将是右上角。如果我将它旋转 180 度,我现在想要得到的值将是右下角。

我需要这个,所以我可以设置另一个 DIV 元素始终保持连接到元素的原始左上角,这样它就会根据它的旋转方式改变它的位置。

谢谢。

4

2 回答 2

3

You can always get the absolute position of an element using:

<element>.getBoundingClientRect()

This gives you the AABB (Axis Aligned Bounding Box, or Min-Max-Box) with the top left corner of the screen as origin. (MDN)

If you need to access the position of the top left corner of your element you can rotate its original position vector too, what is a simple matrix multiplication. You should than keep in mind that the center of rotation is by default the element's center, but it also possible to set this to a different location with css.

Good Luck!

于 2013-04-10T11:45:59.563 回答
0

这是我在遇到同样的问题后得出的解决方案:

// Initial data with TOP AND LEFT OF THE BOUNDING BOX (not x,y of top left point of     the box but left margin of the bounding box   and top margin of the bounding    box)

var top  = Math.ceil($('#' + id).position().top);
var left = Math.ceil($('#' + id).position().left);
var wi   = $('#' + id).css("width").replace("px","");
var he   = $('#' + id).css("height").replace("px","");
var rot  = $(this).data(id + ".ROTACION"); //There I have the applied rotation stored ...

// CALULATIONS

var swapheightwidth= false;

    //Let's keept it first cuad. 

if (rot > 270)
{
    rot = rot - 270;
    swapheightwidth= = true;
}
else if (rot > 180) 
{
    rot = rot - 180;
}
else if (rot > 90) 
{
    swapheightwidth= = true;
    rot = rot - 90;
}

if (swapheightwidth)
{
    var calculatedX=  left + (wi * sin(rot)); 
    var calculatedY=  top + (wi * cos(rot));
}
else
{
    var calculatedX=  left + (he * sin(rot)); 
    var calculatedY=  top + (he * cos(rot));
}

var xbott = left;
var ybott =  Math.ceil(calculatedY);

var xtop=  Math.ceil(calculatedX);
var ytop= top;

    // FINAL CALCULATED POINTS
// xtop  ytop  -> top left
// xbott  ybott   -> bottomleft 

function sin(x) {
    return Math.sin(x / 180 * Math.PI);
}

function cos(x) {
    return Math.cos(x / 180 * Math.PI);
}

干杯

于 2013-05-02T06:50:15.907 回答