在 jQuery 中获取元素 -moz-transform:rotate 值

发布于 2024-12-18 07:13:02 字数 491 浏览 1 评论 0原文

我有一个图层的 CSS 样式:

.element {
    -webkit-transform: rotate(7.5deg);    
     -moz-transform: rotate(7.5deg);    
      -ms-transform: rotate(7.5deg);    
       -o-transform: rotate(7.5deg);   
          transform: rotate(7.5deg);
}

有没有办法通过 jQuery 获取当前旋转值?

我尝试了这个

$('.element').css("-moz-transform")

结果是 matrix(0.991445, 0.130526, -0.130526, 0.991445, 0px, 0px) 这并没有告诉我很多。我想要得到的是 7.5

I have CSS style for a layer:

.element {
    -webkit-transform: rotate(7.5deg);    
     -moz-transform: rotate(7.5deg);    
      -ms-transform: rotate(7.5deg);    
       -o-transform: rotate(7.5deg);   
          transform: rotate(7.5deg);
}

Is there a way to get curent rotation value through jQuery?

I tried this

$('.element').css("-moz-transform")

The result is matrix(0.991445, 0.130526, -0.130526, 0.991445, 0px, 0px) which doesn't tell me a lot. What I'm looking to get is 7.5.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

万人眼中万个我 2024-12-25 07:13:02

这是我使用 jQuery 的解决方案。

这将返回与应用于任何 HTML 元素的旋转相对应的数值。

function getRotationDegrees(obj) {
    var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform")    ||
    obj.css("-ms-transform")     ||
    obj.css("-o-transform")      ||
    obj.css("transform");
    if(matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { var angle = 0; }
    return (angle < 0) ? angle + 360 : angle;
}

angle1 = getRotationDegrees($('#myDiv'));
angle2 = getRotationDegrees($('.mySpan a:last-child'));

ETC...

Here's my solution using jQuery.

This returns a numerical value corresponding to the rotation applied to any HTML element.

function getRotationDegrees(obj) {
    var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform")    ||
    obj.css("-ms-transform")     ||
    obj.css("-o-transform")      ||
    obj.css("transform");
    if(matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { var angle = 0; }
    return (angle < 0) ? angle + 360 : angle;
}

angle1 = getRotationDegrees($('#myDiv'));
angle2 = getRotationDegrees($('.mySpan a:last-child'));

etc...

一身软味 2024-12-25 07:13:02

我在 Twist 的代码中发现了一个错误/功能:函数返回角度。

因此,我在返回 angle 之前添加了一行简单的代码:

if(angle < 0) angle +=360;

结果将是:

function getRotationDegrees(obj) {
    var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform")    ||
    obj.css("-ms-transform")     ||
    obj.css("-o-transform")      ||
    obj.css("transform");
    if(matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { var angle = 0; }

    if(angle < 0) angle +=360;
    return angle;
}

I've found a bug/features in the Twist's code: the function return negative angles.

So I've add a simple line of code before returning the angle:

if(angle < 0) angle +=360;

Than the results will be:

function getRotationDegrees(obj) {
    var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform")    ||
    obj.css("-ms-transform")     ||
    obj.css("-o-transform")      ||
    obj.css("transform");
    if(matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { var angle = 0; }

    if(angle < 0) angle +=360;
    return angle;
}
向地狱狂奔 2024-12-25 07:13:02

我的解决方案(使用 jQuery)

$.fn.rotationInfo = function() {
    var el = $(this),
        tr = el.css("-webkit-transform") || el.css("-moz-transform") || el.css("-ms-transform") || el.css("-o-transform") || '',
        info = {rad: 0, deg: 0};
    if (tr = tr.match('matrix\\((.*)\\)')) {
        tr = tr[1].split(',');
        if(typeof tr[0] != 'undefined' && typeof tr[1] != 'undefined') {
            info.rad = Math.atan2(tr[1], tr[0]);
            info.deg = parseFloat((info.rad * 180 / Math.PI).toFixed(1));
        }
    }
    return info;
};

用法

$(element).rotationInfo(); // {deg: 7.5, rad: 0.13089969389957515}
$(element).rotationInfo().deg; // 7.5

My Solution (using jQuery):

$.fn.rotationInfo = function() {
    var el = $(this),
        tr = el.css("-webkit-transform") || el.css("-moz-transform") || el.css("-ms-transform") || el.css("-o-transform") || '',
        info = {rad: 0, deg: 0};
    if (tr = tr.match('matrix\\((.*)\\)')) {
        tr = tr[1].split(',');
        if(typeof tr[0] != 'undefined' && typeof tr[1] != 'undefined') {
            info.rad = Math.atan2(tr[1], tr[0]);
            info.deg = parseFloat((info.rad * 180 / Math.PI).toFixed(1));
        }
    }
    return info;
};

Usage:

$(element).rotationInfo(); // {deg: 7.5, rad: 0.13089969389957515}
$(element).rotationInfo().deg; // 7.5
白芷 2024-12-25 07:13:02

这是 Twist 功能的插件版本。另外,条件 if(matrix !== 'none') 对我不起作用。所以我添加了类型检查:

(function ($) {
    $.fn.rotationDegrees = function () {
         var matrix = this.css("-webkit-transform") ||
    this.css("-moz-transform")    ||
    this.css("-ms-transform")     ||
    this.css("-o-transform")      ||
    this.css("transform");
    if(typeof matrix === 'string' && matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { var angle = 0; }
    return angle;
   };
}(jQuery));

使用如下:

var rotation = $('img').rotationDegrees();

Here is a plug-in version of Twist's function. Also, the conditional if(matrix !== 'none') did not work for me. So I have added type-checking:

(function ($) {
    $.fn.rotationDegrees = function () {
         var matrix = this.css("-webkit-transform") ||
    this.css("-moz-transform")    ||
    this.css("-ms-transform")     ||
    this.css("-o-transform")      ||
    this.css("transform");
    if(typeof matrix === 'string' && matrix !== 'none') {
        var values = matrix.split('(')[1].split(')')[0].split(',');
        var a = values[0];
        var b = values[1];
        var angle = Math.round(Math.atan2(b, a) * (180/Math.PI));
    } else { var angle = 0; }
    return angle;
   };
}(jQuery));

Use as follows:

var rotation = $('img').rotationDegrees();
迟到的我 2024-12-25 07:13:02

CSS transform 属性将始终返回一个矩阵值,因为旋转、倾斜、缩放等只是简化操作的简写,不必每次都计算矩阵值,但是矩阵是由浏览器计算并作为矩阵应用的,完成此操作后,如果不再次重新计算矩阵,则无法再返回按角度旋转的度数。

为了使这种计算更容易,有一个名为 Sylvester 的 JavaScript 库,它是为了简单的矩阵计算而创建的,请尝试查看它以从矩阵值中获取旋转度数。

另外,如果你在 javascript 中编写一个旋转函数来将旋转角度转换为矩阵,它可能看起来像这样(这使用西尔维斯特进行最后的计算):

var Transform = {
    rotate: function(deg) {
        var rad = parseFloat(deg) * (Math.PI/180),
            cos_theta = Math.cos(rad),
            sin_theta = Math.sin(rad);

        var a = cos_theta,
            b = sin_theta,
            c = -sin_theta,
            d = cos_theta;

        return $M([
          [a, c, 0],
          [b, d, 0],
          [0, 0, 1]
        ]);
    }
};

现在你真正要做的就是对该函数进行反向工程并你是金子:-)

The CSS tranform property will always return a matrix value, as rotate, skew, scale etc. is just shorthand for doing things easier, and not having to calculate the matrix value everytime, however the matrix is calculated by the browser and applied as a matrix, and when that is done it can no longer return the rotated degree by angle without recalculating the matrix back again.

To make such calcualtions easier there is a javascript library called Sylvester that was created for the purpose of easy matrix calculation, try looking at that to get the rotation degree from the matrix value.

Also, if you where to write a rotate function in javascript to translate rotational degrees to a matrix, it would probably look something like this (this uses sylvester for the last calculation) :

var Transform = {
    rotate: function(deg) {
        var rad = parseFloat(deg) * (Math.PI/180),
            cos_theta = Math.cos(rad),
            sin_theta = Math.sin(rad);

        var a = cos_theta,
            b = sin_theta,
            c = -sin_theta,
            d = cos_theta;

        return $M([
          [a, c, 0],
          [b, d, 0],
          [0, 0, 1]
        ]);
    }
};

Now all you really have to do is reverse enginer that function and you're golden :-)

〆凄凉。 2024-12-25 07:13:02

我已经对这个工作代码进行了修改,以获得 3D 上的rotateX YZ 或用于2D 变换的rotateZ 。感谢 mihn 提供的基本代码,我几乎没有使用实际的 jquery 2.2.3 进行更新。
我目前在我自己的项目中使用这个解决方案。

https://jsfiddle.net/bragon95/49a4h6e9/

    //
//Thanks: Adapted on base code from mihn http://stackoverflow.com/a/20371725
//

function getcsstransform(obj)
{
    var isIE = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent);

  var TType="undefined",
        rotateX = 0,
        rotateY = 0,
      rotateZ = 0;

  var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform") ||
    obj.css("-ms-transform") ||
    obj.css("-o-transform") ||
    obj.css("transform");
  if (matrix!==undefined && matrix !== 'none')
  {
        // if matrix is 2d matrix
    TType="2D";
    if (matrix.indexOf('matrix(') >= 0)
    {
      var values = matrix.split('(')[1].split(')')[0];
      if (isIE)  //case IE
      {
        angle = parseFloat(values.replace('deg', STR_EMPTY));
      }else
      {
        values = values.split(',');
        var a = values[0];
        var b = values[1];
        var rotateZ = Math.round(Math.atan2(b, a) * (180 / Math.PI));
      }
    }else
    {
      // matrix is matrix3d
      TType="3D";
      var values = matrix.split('(')[1].split(')')[0].split(',');
      var sinB = parseFloat(values[8]);
      var b = Math.round(Math.asin(sinB) * 180 / Math.PI);
      var cosB = Math.cos(b * Math.PI / 180);
      var matrixVal10 = parseFloat(values[9]);
      var a = Math.round(Math.asin(-matrixVal10 / cosB) * 180 / Math.PI);
      var matrixVal1 = parseFloat(values[0]);
      var c = Math.round(Math.acos(matrixVal1 / cosB) * 180 / Math.PI);
      rotateX = a;
      rotateY = b;
      rotateZ = c;
    }
  }

    return  { TType: TType, rotateX: rotateX,  rotateY: rotateY,  rotateZ: rotateZ };
};

mAngle = getcsstransform($("#Objet3D"));
if (mAngle.TType=="2D")
{
    $("#Result").html("Transform 2D [rotateZ=" + mAngle.rotateZ + "°]");
}else
{
    $("#Result").html("Transform 3D [rotateX=" + mAngle.rotateX + "°|rotateY=" + mAngle.rotateY + "°|rotateZ=" + mAngle.rotateZ + "°]");
}

I have make a fiddle with this working code to get rotateX Y Z on a 3D , or rotateZ for a 2D transform. Thanks to mihn for the base code that i have little updated with actual jquery 2.2.3.
I currently use this solution for my own projects.

https://jsfiddle.net/bragon95/49a4h6e9/

    //
//Thanks: Adapted on base code from mihn http://stackoverflow.com/a/20371725
//

function getcsstransform(obj)
{
    var isIE = /(MSIE|Trident\/|Edge\/)/i.test(navigator.userAgent);

  var TType="undefined",
        rotateX = 0,
        rotateY = 0,
      rotateZ = 0;

  var matrix = obj.css("-webkit-transform") ||
    obj.css("-moz-transform") ||
    obj.css("-ms-transform") ||
    obj.css("-o-transform") ||
    obj.css("transform");
  if (matrix!==undefined && matrix !== 'none')
  {
        // if matrix is 2d matrix
    TType="2D";
    if (matrix.indexOf('matrix(') >= 0)
    {
      var values = matrix.split('(')[1].split(')')[0];
      if (isIE)  //case IE
      {
        angle = parseFloat(values.replace('deg', STR_EMPTY));
      }else
      {
        values = values.split(',');
        var a = values[0];
        var b = values[1];
        var rotateZ = Math.round(Math.atan2(b, a) * (180 / Math.PI));
      }
    }else
    {
      // matrix is matrix3d
      TType="3D";
      var values = matrix.split('(')[1].split(')')[0].split(',');
      var sinB = parseFloat(values[8]);
      var b = Math.round(Math.asin(sinB) * 180 / Math.PI);
      var cosB = Math.cos(b * Math.PI / 180);
      var matrixVal10 = parseFloat(values[9]);
      var a = Math.round(Math.asin(-matrixVal10 / cosB) * 180 / Math.PI);
      var matrixVal1 = parseFloat(values[0]);
      var c = Math.round(Math.acos(matrixVal1 / cosB) * 180 / Math.PI);
      rotateX = a;
      rotateY = b;
      rotateZ = c;
    }
  }

    return  { TType: TType, rotateX: rotateX,  rotateY: rotateY,  rotateZ: rotateZ };
};

mAngle = getcsstransform($("#Objet3D"));
if (mAngle.TType=="2D")
{
    $("#Result").html("Transform 2D [rotateZ=" + mAngle.rotateZ + "°]");
}else
{
    $("#Result").html("Transform 3D [rotateX=" + mAngle.rotateX + "°|rotateY=" + mAngle.rotateY + "°|rotateZ=" + mAngle.rotateZ + "°]");
}
£噩梦荏苒 2024-12-25 07:13:02

如果您按照您所描述的方式执行此操作,那么这是您实际修改对象变换的唯一位置,那么由于您的浏览器不能同时是所有 4 种浏览器,因此您分配的一些前缀值是仍然完全按照您分配的那样。
例如,如果您使用 webkit,那么 this.css('-o-transform') 仍然会返回 'rotate(7.5deg)',所以它只是一个将其与 /rotate\((.*)deg\)/ 进行匹配的问题。

这对我来说效果很好:我总是分配 5 种 css 样式,并读回所有五种样式,希望其中至少一种不会受到影响。我不确定如果样式是在 CSS(而不是 JS)中设置的,这是否有效。

If you do this in the way you described, any this is the only place where you actually modify transform of the object, then since your browser can not be all 4 kinds of browsers at the same time, some of the prefixed values you assigned are still exactly as you assigned them.
So for example if you use webkit, then this.css('-o-transform') will still return 'rotate(7.5deg)', so it is just a matter of matching it against /rotate\((.*)deg\)/.

This worked fine for me : I always assign 5 css styles, and read back all five styles, hoping that at least one of them will be untouched. I am not sure if this works if the styles are set in CSS (not in JS) though.

少女的英雄梦 2024-12-25 07:13:02

您也可以将 var angle = Math.round(Math.atan2(b, a) * (180/Math.PI)); 替换为 var angle = Math.round(Math.acos (a) * (180/Math.PI));

Also you could replace var angle = Math.round(Math.atan2(b, a) * (180/Math.PI)); to var angle = Math.round(Math.acos(a) * (180/Math.PI));

染墨丶若流云 2024-12-25 07:13:02

由于我经常需要将 jQuery 与 TweenMax 一起使用,并且 TweenMax 已经处理了各种类型转换字符串的所有解析以及兼容性问题,因此我编写了一个小型 jquery 插件 这里(更多的是 gsap 的总结),可以直接访问这些值,如下所示:

$('#ele').transform('rotationX') // returns 0
$('#ele').transform('x')         // returns value of translate-x

您可以获取/设置的属性列表,以及它们的属性初始属性:

perspective: 0
rotation: 0
rotationX: 0
rotationY: 0
scaleX: 1
scaleY: 1
scaleZ: 1
skewX: 0
skewY: 0
x: 0
y: 0
z: 0
zOrigin: 0

从我的其他答案粘贴,希望这有帮助。

Since I constantly need to use jQuery together with TweenMax and since TweenMax already took care of all the parsing of various types of transformation strings as well as compatibility issues, I wrote a tiny jquery plugin here (more of a wrap up of gsap's) that could directly access these values like this:

$('#ele').transform('rotationX') // returns 0
$('#ele').transform('x')         // returns value of translate-x

The list of properties you could get/set, along with their initial properties:

perspective: 0
rotation: 0
rotationX: 0
rotationY: 0
scaleX: 1
scaleY: 1
scaleZ: 1
skewX: 0
skewY: 0
x: 0
y: 0
z: 0
zOrigin: 0

Paste from my other answer, hope this helps.

情话墙 2024-12-25 07:13:02

如果您愿意使用内联样式来进行此转换,那么您可以使用 jQuery 来获取样式标记的内容:

parseInt($(  /*TODO*/  ).attr('style').split('rotate(')[1].split('deg)')[0]);

If you're willing to use in-line styling for just this transformation, then you can use jQuery to get the contents of the style tag:

parseInt($(  /*TODO*/  ).attr('style').split('rotate(')[1].split('deg)')[0]);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文