2014-12-05 59 views
0

我正在創建一個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); 
    }()); 

謝謝!

回答

0

您不應該使用addAttribute/removeAttribute來添加/刪除類/樣式。 (HTML屬性決定了HTML的當前狀態,但關於當前DOM狀態的權威信息是在DOM節點屬性中)See this question.)相反,如果您不想使用任何實用程序庫(如jQuery),請使用HTMLElement.style屬性設置內聯樣式和Element.classList API來添加/刪除類。

編輯:乍一看,我在代碼中看到一個額外的錯誤。您正在安排部分操作在0.5秒後發生,並使用原始變量值,但是您需要更改這些值。在這種情況下你需要做的是將所需的值傳遞給setTimeout作爲附加參數。

Here's your codepen, updated with my suggestions.它仍然不能正常工作,但你所問的部分似乎是固定的。 Here's another codepen其中我修改了代碼以使其更透明,但它也無法正常工作,我沒有時間去調試它。

+0

雖然樣式現在正在清除,但它看起來像'flip-bottom'類仍未被刪除。你會注意到,因爲這個類沒有被移除,下半部分只是不斷翻轉,並且沒有'z-index'設置,最上面的跨度將顯示在最上面。 – EnergyMud 2014-12-05 10:39:53

+0

該類正在被刪除所有權利,只需在移除後插入'console.log(divs [i] .children [1] .classList.contains('flip-bottom'));''。你的算法必須有另一個問題。 – hon2a 2014-12-05 11:19:30

+0

Chrome檢查器仍在顯示元素上的「flip-bottom」類,如果它被移除,不應該將動畫應用於最近的元素上? – EnergyMud 2014-12-05 11:46:42