我看到了 Ilya 关于矩阵的评论,这可能是件好事。鉴于我在矩阵数学方面遇到困难,基于字符串的解决方案就在我的小巷里。
我在大约半小时内把它扔在一起,但它似乎运作良好。我假设您只会捕获鼠标移动并更新翻译值。我创建了 toObject 方法以防你想做一些更高级的动画。
我认为如果你打算走这条路,你应该重新考虑不想使用框架。
(function() {
var setTransFunc, getTransFunc;
// make sure cross browser...
// I don't know if this is nescessary. Every browser I tried worked on the first options.
(function () {
var testElem = document.createElement('DIV');
if (testElem.style.transform !== undefined) {
setTransFunc = function (elem, str) {
elem.style.transform = str;
}
getTransFunc = function (elem) {
return elem.style.transform;
}
}
else if (testElem.style.webkitTransform !== undefined) {
setTransFunc = function (elem, str) {
elem.style.webkitTransform = str;
}
getTransFunc = function (elem) {
return elem.style.webkitTransform;
}
}
else if (testElem.style.msTransform !== undefined) {
setTransFunc = function (elem, str) {
elem.style.msTransform = str;
}
getTransFunc = function (elem) {
return elem.style.msTransform;
}
}
else {
throw ('unable to detect set/get methods for transform style.');
}
}).call();
// constructor
var _tranZ = function (elem) {
this.elem = (typeof elem == 'string') ? document.getElementById(elem) : elem;
};
(function () {
this.elem = null;
// sets transform style
this.set = function (str) {
setTransFunc(this.elem, str);
return this;
}
// gets string of transform style
this.get = function () {
return getTransFunc(this.elem);
}
// adds a trasnform
this.add = function (str) {
this.set(this.get() + ' ' + str);
return this;
}
// removes a transform
this.remove = function (name) {
var re = new RegExp(name + "\\([^)]*\\)", "gi");
console.log(re);
this.set(this.get().replace(re, ""));
return this;
}
// represent transforms as object. Might be easier later on to animate with this.
this.getTransformObject = function () {
var str = this.get(),
re = /(\w+)\s*\(([^)]*)\)/g,
match, obj = {};
while (match = re.exec(str)) {
obj[match[1]] = {
parameters: match[2].split(/\s*,\s*/)
}
}
return obj;
}
}).call(_tranZ.prototype);
// add a window module
window.tranZ = function (elem) {
return new _tranZ(elem);
};
})();