Translate all children of element along X-axis
I'd like to translate all the children of a given element, say by 100 p开发者_Go百科ixels along the X-axis.
A couple of caveats:
- I'd prefer not to use any jQuery or other libraries as I'm using this in a library that should be standalone if possible
- This will be entirely for Chromium. In fact, I'd prefer using
-webkit-transform: translate(...)
to what I'm doing right now (since-webkit-transform
will work even without relative positioning)
I currently can make it work using the following ugly, hacky code:
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);
Is there any better (read: cleaner) way to accomplish this? Or, better yet, is there a way I can accomplish this using only -webkit-transform
(i.e. no position:relative)?
Thanks.
There is a JS property called webkitTransform and it holds the actual CSS declaration of a transform ("rotate(30deg)", "translate(10px, 20px)" etc.) but reading it each time using a regular expression might not be the fastest thing to do so you might just as well stash the current translation away in a new property.
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);
This assumes that the elements in question won't have any other transformation set - otherwise, things get a little trickier and you will need to make sure the other transformations don't get dropped (again, that would be best accomplished by memorizing all the other transformation properties as JS properties because parsing the declaration is a little tricky and certainly not as fast).
精彩评论