简体   繁体   中英

How do I get the absolute value of translate3d?

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

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

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

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM