How do I get the absolute value of translate3d?

好久不见. 提交于 2019-12-11 14:29:26

问题


How would I go about converting a negative translate3d value into a positive number?

For example:

var val = $m('slider').style.webkitTransform;
console.log(val); // this returns a number like: translate3d(-93px, 0, 0);

How would I go about converting the values into positive numbers so that my output is:

translate3d(93px, 0, 0); // positive 93

回答1:


It is better to keep track of your coords also in JS if you can, but if this isnt possible, you need to parse out the individual values from the transform matrix...

Demo

If you get the computed style of the transform (not just the .style property) using getComputedStyle it will return a matrix:

// adapted from jQuery solution at https://stackoverflow.com/questions/7982053/get-translate3d-values-of-a-div
function getTransform(el) {
    var transform = window.getComputedStyle(el, null).getPropertyValue('-webkit-transform');
    var results = transform.match(/matrix(?:(3d)\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))(?:, (-{0,1}\d+)), -{0,1}\d+\)|\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))\))/);

    if(!results) return [0, 0, 0];
    if(results[1] == '3d') return results.slice(2,5);

    results.push(0);
    return results.slice(5, 8); // returns the [X,Y,Z,1] values
}


var translation = getTransform( $m('slider') );
var translationX = translation[0];
var absX = Math.abs(translationX);



回答2:


This is an example of how you could separate all of the values using split, parsing the integer values using parseInt and then getting the absolute value using abs()

Working fiddle: http://jsfiddle.net/bXgCP/

var mystr = "93px, 0, 10";

var myarr = mystr.split(",");
var finalStr = '';

for (var i=0;i<myarr.length;i++)
{ 

    myarr[i] = Math.abs(parseInt(myarr[i]),10);
}

finalStr = myarr.join(); // put the values back with the `,` format



回答3:


The answer by Adam has a bug: It cannot handle decimal values like this:

matrix(1, 0, 0, 1, 100.000002649095, 100.000002649095) 

Adapted regex to allow it:

function getTransform(el) {
    var transform = window.getComputedStyle(el, null).getPropertyValue('-webkit-transform');
    var results = transform.match(/matrix(?:(3d)\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}\d+))(?:, (-{0,1}\d+))(?:, (-{0,1}\d+)), -{0,1}\d+\)|\(-{0,1}\d+(?:, -{0,1}\d+)*(?:, (-{0,1}.+))(?:, (-{0,1}.+))\))/);

    if(!results) return [0, 0, 0];
    if(results[1] == '3d') return results.slice(2,5);

    results.push(0);
    return results.slice(5, 8); // returns the [X,Y,Z,1] values
}


来源:https://stackoverflow.com/questions/15622466/how-do-i-get-the-absolute-value-of-translate3d

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