如何获得translate3d的绝对值? [英] How do I get the absolute value of translate3d?

查看:163
本文介绍了如何获得translate3d的绝对值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何将负的translate3d值转换为正数?

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

例如:

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


推荐答案

你的协调也在JS,如果你可以,但如果这是不可能的,你需要解析来自变换矩阵的单个值 ...

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...

演示

如果您获得计算的转换风格(不仅仅是 .style 属性)使用 getComputedStyle ,它将返回一个矩阵:

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 http://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);

这篇关于如何获得translate3d的绝对值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆