我如何将负的 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
最佳答案
如果可以的话,最好也在 JS 中跟踪你的坐标,但如果这不可能,你需要 parse out the individual values from the transform matrix ...
如果您使用 getComputedStyle
获得转换的计算样式(不仅仅是 .style
属性),它将返回一个矩阵:
// 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);
关于javascript - 如何获得 translate3d 的绝对值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15622466/