【问题标题】:Translate all children of element along X-axis沿 X 轴平移元素的所有子元素
【发布时间】:2023-04-10 19:21:01
【问题描述】:

我想平移给定元素的所有子元素,例如沿 X 轴平移 100 个像素。

几个注意事项:

  1. 我不想使用任何 jQuery 或其他库,因为我在一个库中使用它,如果可能的话应该是独立的
  2. 这将完全适用于 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(即没有位置:相对)来完成此任务?

谢谢。

【问题讨论】:

    标签: javascript webkit translation positioning transform


    【解决方案1】:

    有一个名为 webkitTransform 的 JS 属性,它包含变换的实际 CSS 声明(“rotate(30deg)”、“translate(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);
    

    这假设有问题的元素不会有任何其他转换集 - 否则,事情会变得有点棘手,您需要确保其他转换不会被丢弃(同样,最好通过将所有其他转换属性记住为 JS 属性,因为解析声明有点棘手,而且肯定没有那么快)。

    【讨论】:

    • 与其记住其他属性,不如将原始变换转换为矩阵,然后跟踪矩阵堆栈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-19
    • 2019-09-22
    • 1970-01-01
    • 2019-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多