沿 X 轴平移元素的所有子元素
我想平移给定元素的所有子元素,例如沿 X 轴平移 100 像素。
一些警告:
- 我不想使用任何 jQuery 或其他库,因为我在一个应该是独立的库中使用它(如果可能的话)
- 这将完全适用于 Chromium。事实上,我更喜欢使用
-webkit-transform:translate(...)
而不是我现在正在做的事情(因为-webkit-transform
甚至可以工作没有相对定位)
我目前可以使用以下丑陋的、hacky 代码让它工作:
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);
有没有更好的(阅读:更干净的)方法来完成这个?或者,更好的是,有没有一种方法可以仅使用 -webkit-transform
(即没有position:relative)来完成此任务?
谢谢。
I'd like to translate all the children of a given element, say by 100 pixels 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
有一个名为 webkitTransform 的 JS 属性,它包含变换的实际 CSS 声明(“rotate(30deg)”、“translate(10px, 20px)”等),但每次使用正则表达式读取它可能不是最快的因此,您不妨将当前的翻译存放在新的属性中。
这假设所讨论的元素不会有任何其他转换集 - 否则,事情会变得有点棘手,您需要确保其他转换不会被删除(同样,最好通过记住所有其他转换属性作为 JS 属性,因为解析声明有点棘手,而且肯定没有那么快)。
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.
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).