2012-02-12 165 views
0

我有一個JavaScript文件,用於嘗試爲下拉菜單設置動畫。我在該文件集中的「切換」功能在我點擊某個div時運行。下面是我使用的腳本:Javascript「For」循環不工作?

var up = true; 
     function Toggle(x) 
    { 
     if (up) 
     { 
      for (var i = x.offsetTop; i <= 0; i++) 
      { 
       x.style.top = i; 
       if (i == 0) 
       { 
        up = false; 
       } 
      } 
     } 

     else if (up == false) 
     { 
      for (var i = x.offsetTop; i >= -50; i--) 
      { 
       x.style.top = i; 
       if (i == -50) 
       { 
        up = true; 
       } 
      } 
     } 
    } 

在HTML DIV我想動畫,我有「點擊」屬性設置爲「的onclick =切換(本)」。第一個for循環的工作原理(它將div的頂部偏移量設置爲0)。但是,第二個for循環不會設置offsetTop。我知道for循環正在激活,因爲我測試了它,並且它給了我0到-50之間的每個整數。爲什麼不設置偏移位置?

+1

如果你想看動畫的發生,你將需要包含某種延遲。您還需要爲頂部樣式屬性指定一個單位,例如'px'。 – 2012-02-12 21:03:58

回答

1

1)您必須指定一個單元的頂部,即:你使用的setInterval或setTimeout的

就像你問一個例子x.style.top = i +"px"

2)你的功能將不能代替動畫。對於我的一個項目,我不會這樣做,但我保留了自己的功能,讓您更熟悉代碼。 我使用的setTimeout,而不是setInterval的,因爲不需要時的setInterval必須清除和setTimeout的是剛剛推出一個時間:

var Toggle = (function() { // use scope to define up/down 
    var up = true; 
    return function(element) { 
     var top = parseInt(element.style.top, 10); // element.offsetTop ? 
     if (!top) { 
      top = 0; 
     } 

     if (up) { 
      if (element.offsetTop < 0) { // if we are not at 0 and want to get up 
       element.style.top = (top+1) + "px"; 
       setTimeout(function() { Toggle(element); }, 10); // recall the function in 10 ms 
      } else { // we change up value 
       up = !up; 
      } 
     } 
     else { 
      if (element.offsetTop > -50) { 
       element.style.top = (top-1) + "px"; 
       setTimeout(function() { Toggle(element); }, 10); // recall the function in 10 ms 
      } else { 
       up=!up; 
      } 
     } 
    } 
})(); 
+0

你可以舉一個setInterval的例子嗎?我知道如何在C#中處理這個問題,但我對JavaScript很新。 – 2012-02-12 21:12:41

+0

通過編輯向您展示setTimeout的示例 – dievardump 2012-02-12 21:35:36

0

你不得不使用x.style.top = i + 'px'爲頂部和類似CSS屬性必須定義類型(pxem,%等),除非它們是0,因爲在任何情況下都是0。

但是您的腳本實際上會將對齊div直接指定爲-50px,因爲您不必在這些迭代步驟之間等待。

我建議使用像jQuery這樣的庫來使用它的animate()方法。

function Toggle(obj) { 
    $(obj).animate({ 
    top: parseInt($(obj).css('top')) === 0 ? '-50px' : '0px' 
    }) 
}