Javascript 沿X轴平移元素的所有子元素
我想平移给定元素的所有子元素,比如沿X轴平移100像素 有几个注意事项:Javascript 沿X轴平移元素的所有子元素,javascript,webkit,translation,positioning,transform,Javascript,Webkit,Translation,Positioning,Transform,我想平移给定元素的所有子元素,比如沿X轴平移100像素 有几个注意事项: 我不希望使用任何jQuery或其他库,因为我在一个可能的情况下应该是独立的库中使用它 这将完全用于铬。事实上,我更喜欢使用-webkit transform:translate(…),以适应我现在正在做的事情(因为-webkit transform即使没有相对定位也能工作) 目前,我可以使用以下难看的黑客代码使其正常工作: function translateElementChildrenBy(element, trans
-webkit transform:translate(…)
,以适应我现在正在做的事情(因为-webkit transform
即使没有相对定位也能工作)function translateElementChildrenBy(element, translation)
{
var children = element.children;
for(var i = 0; i < children.length; ++i)
{
var curPos = parseInt(children[i].style.left);
if(isNaN(curPos)) curPos = 0;
children[i].style.position = "relative";
children[i].style.left = "" + (curPos + translation);
}
}
translateElementChildrenBy(document.body, 100);
函数translateElementChildrenBy(元素,翻译)
{
var children=element.children;
对于(变量i=0;i
有没有更好的方法来实现这一点?或者,更好的是,是否有一种方法可以仅使用-webkit transform
(即无位置:相对)来实现这一点
谢谢。有一个名为WebKittTransform的JS属性,它保存转换的实际CSS声明(“旋转(30deg)”,“平移(10px,20px)”等),但每次使用正则表达式读取它可能不是最快的事情,因此您不妨将当前的翻译隐藏在一个新属性中
function translateElementChildrenBy(element, translation)
{
var children = element.children;
for (var i = 0; i < children.length; ++i)
{
var child = children[i];
var currentTranslation = child._currentTranslation || 0;
child._currentTranslation = currentTranslation + translation;
child.style.webkitTransform = "translate(" + child._currentTranslation + ")";
}
}
translateElementChildrenBy(document.body, 100);
函数translateElementChildrenBy(元素,翻译)
{
var children=element.children;
对于(变量i=0;i
这假设所讨论的元素没有任何其他转换集——否则,事情会变得有点棘手,您需要确保其他转换不会被删除(同样,最好是将所有其他转换属性作为JS属性来存储,因为解析声明有点棘手,而且肯定没有那么快)。有一个名为WebKittTransform的JS属性,它保存转换的实际CSS声明(“旋转(30deg)”,“平移(10px,20px)”等。)但是每次使用正则表达式读取它可能不是最快的事情,因此您最好将当前的翻译隐藏在新属性中
function translateElementChildrenBy(element, translation)
{
var children = element.children;
for (var i = 0; i < children.length; ++i)
{
var child = children[i];
var currentTranslation = child._currentTranslation || 0;
child._currentTranslation = currentTranslation + translation;
child.style.webkitTransform = "translate(" + child._currentTranslation + ")";
}
}
translateElementChildrenBy(document.body, 100);
函数translateElementChildrenBy(元素,翻译)
{
var children=element.children;
对于(变量i=0;i
这假设所讨论的元素没有任何其他转换集——否则,事情会变得有点棘手,您需要确保其他转换不会被删除(同样,最好是将所有其他转换属性作为JS属性存储起来,因为解析声明有点棘手,而且肯定没有那么快).与其记住其他属性,不如将原始变换转换为矩阵,然后跟踪矩阵堆栈。与其记住其他属性,不如将原始变换转换为矩阵,然后跟踪矩阵堆栈