为什么不执行嵌套 setTimeout 中的 removeAttribute 调用

Why aren't removeAttribute calls inside of nested setTimeouts being executed

本文关键字:removeAttribute 调用 中的 setTimeout 执行 嵌套 为什么不      更新时间:2023-09-26

我正在创建一个 rolodex 类型的动画,我正在使用计时器为 3D 动画设置一个类,并动态设置 z 索引,以便元素在需要时相互叠加和叠加。每一秒我都期望底部跨度(divs.children[1](设置类和样式属性,然后在该秒之间,我希望底部删除属性,上半部分(divs.children[0](开始动画。

当我使用以下代码时,每次调用 hideTop()showTop()showBottom() 都按预期工作,但无论何时调用hideBottom(),样式或类属性都不会被删除。我也尝试过使用setAttribute("style", ""),但无济于事。我之前使用setInterval(function() { ... }, 1000)也产生了相同的行为。

代码笔也是。

    var i = 0;
    var x = 100;
    var firstRun = true;
    var digit = document.getElementById("digit");
    var divs = digit.getElementsByTagName("div");
    divs[0].children[0].setAttribute("style", "-webkit-transform: rotateX(0deg);");
    (function scrollRolodex() {
        function showTop(i, x) {
            divs[i].children[0].setAttribute("style", "z-index: " + ((i * x) + 10));
            divs[i].children[0].setAttribute("class", "flip-top");
        }
        function hideTop(i) {
            divs[i].children[0].removeAttribute("style");
            divs[i].children[0].removeAttribute("class");
        }
        function showBottom(i, x) {
            divs[i].children[1].setAttribute("style", "z-index: " + ((i * x) + 5));
            divs[i].children[1].setAttribute("class", "flip-bottom");       
        }
        function hideBottom(i) {
            divs[i].children[1].removeAttribute("style");
            divs[i].children[1].removeAttribute("class");
        }
        if (i < divs.length) { 
            if (i == 0 && !firstRun) {
                hideTop(divs.length - 1);
            } else if (i > 0) {
                hideTop(i - 1); 
            }
            showBottom(i, x);
            window.setTimeout(function() {
                hideBottom(i);
                if (i != (divs.length - 1)) {
                    showTop(i, x);
                } else {
                    showTop(divs.length - 1, x);
                }
            }, 500);
            if (i == divs.length - 1) {
                i = 0;
                x = 100;
                firstRun = false;
            } else {
                i++;
                x++;
            }
        }
        setTimeout(scrollRolodex, 1000);
    }());

谢谢!

您不应该使用 addAttribute/removeAttribute 来添加/删除类/样式。(HTML 属性确定 HTML 的当前状态,但有关当前 DOM 状态的权威信息位于 DOM 节点属性中。请参阅此问题。相反,如果您不想使用任何实用程序库(如 jQuery(,请使用 HTMLElement.style 属性设置内联样式,并使用 Element.classList API 添加/删除类。

编辑:第二眼,我在您的代码中看到一个额外的错误。您计划在 0.5 秒后使用原始变量值执行部分操作,但随后更改了这些值。在这种情况下,您需要做的是将所需的值作为附加参数传递给setTimeout

这是你的代码笔,根据我的建议进行了更新。它仍然无法正常工作,但是您询问的部分似乎已修复。这是另一个代码笔,我在其中修改了代码以使其更加透明,但它也不起作用,我没有时间调试它。