我如何将负的translate3d值转换为正数?
例如:
var val = $m('slider').style.webkitTransform;
console.log(val); // this returns a number like: translate3d(-93px, 0, 0);
我如何将值转换为正数,以便输出为:
translate3d(93px, 0, 0); // positive 93
答案 0 :(得分:2)
如果可以的话,最好还是在JS中跟踪你的坐标,但如果不可能,你需要parse out the individual values from the transform matrix ......
如果使用.style
得到变换的计算样式(不仅仅是getComputedStyle
属性),它将返回一个矩阵:
// 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);
答案 1 :(得分:1)
这是一个示例,说明如何使用split
分隔所有值,使用parseInt
解析整数值,然后使用abs()
获取绝对值
工作小提琴: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
答案 2 :(得分:1)
Adam的答案有一个错误:它不能像这样处理小数值:
matrix(1, 0, 0, 1, 100.000002649095, 100.000002649095)
改编正则表达式以允许它:
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
}