【问题标题】:JavaScript/jQuery: How to get actual original position of an element (DIV) after it's been rotatedJavaScript/jQuery:如何在旋转后获取元素 (DIV) 的实际原始位置
【发布时间】:2013-04-10 11:10:06
【问题描述】:

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

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

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

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

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

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

谢谢。

【问题讨论】:

    标签: javascript jquery rotation position offset


    【解决方案1】:

    您始终可以使用以下方法获取元素的绝对位置:

    <element>.getBoundingClientRect()

    这将为您提供以屏幕左上角为原点的 AABB(Axis Aligned Bounding Box,或 Min-Max-Box)。 (MDN)

    如果您需要访问元素左上角的位置,您也可以旋转其原始位置向量,什么是简单的矩阵乘法。您应该记住,默认情况下旋转中心是元素的中心,但也可以使用 css 将其设置为不同的位置。

    祝你好运!

    【讨论】:

      【解决方案2】:

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

      // 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);
      }
      

      干杯

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-08-11
        • 2016-08-22
        • 2018-06-18
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多