我正在創建一個rolodex類型的動畫,我正在使用定時器爲3D動畫設置一個類並動態設置z-index以便元素在需要時彼此重疊和互相覆蓋。每一秒我都期待底部範圍(divs.children[1]
)設置了類和樣式屬性,然後在這一秒之間的中間,我期望底部移除屬性,上半部分(divs.children[0]
)開始動畫。爲什麼在正在執行的嵌套setTimeouts內部不執行removeAttribute調用
當我使用下面的代碼,每次調用hideTop()
,showTop()
,並如預期showBottom()
工作,但每當hideBottom()
被調用,無論是樣式或類別屬性被刪除。我也嘗試使用setAttribute("style", "")
,但無濟於事。之前我使用setInterval(function() { ... }, 1000)
也產生了相同的行爲。
Codepen以及。
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);
}());
謝謝!
雖然樣式現在正在清除,但它看起來像'flip-bottom'類仍未被刪除。你會注意到,因爲這個類沒有被移除,下半部分只是不斷翻轉,並且沒有'z-index'設置,最上面的跨度將顯示在最上面。 – EnergyMud 2014-12-05 10:39:53
該類正在被刪除所有權利,只需在移除後插入'console.log(divs [i] .children [1] .classList.contains('flip-bottom'));''。你的算法必須有另一個問題。 – hon2a 2014-12-05 11:19:30
Chrome檢查器仍在顯示元素上的「flip-bottom」類,如果它被移除,不應該將動畫應用於最近的元素上? – EnergyMud 2014-12-05 11:46:42