2016-11-15 167 views
0

我有這個代碼,我試圖讓其中一個div動畫。 div應該向下移動,然後降低20%後應該開始向上移動,然後再向下移動,等等。Javascript的setInterval()只運行一次函數

問題是,看起來,代碼只運行一次。這意味着div只下跌2%,然後停留在那個位置。

的Javascript

var head = document.getElementById('char_furuta_head'); 
function anime() { 
    var direction = 1; /* 1 = down, -1 = up */ 
    setInterval(frame, 1000); 
    function frame() { 
     str = head.style.top; 
     str = substring(0,str.length); 
     var lel = parseInt(str); 
     console.log(lel); 

     if (direction == 1) { 
      lel += 2; 
      head.style.top = lel + '%'; 
      if(lel == 20) { direction = -1; }; 
     } else { 
      lel -= 2; 
      head.style.top = lel + '%'; 
      if(lel == 0) { direction = 1; }; 
     } 
    } 
} 
+1

它只有一次運行的可能性較小,而且更有可能您的邏輯只會導致頁面發生重大更改一次。 –

+0

console.log()是你的朋友...用它來看看會發生什麼... – epascarello

回答

3

你誤診的問題。

間隔運行良好。

您需要正確調試它。 Add console.log statements to see when functions are called and what the values of your variables are

var lel = head.style.top; 
    lel += 2; 
    head.style.top = lel + '%'; 

第一次調用:

  1. lel是一個空字符串
  2. lel2
  3. head.style.top2%

第二時間:

  1. lel2%
  2. lel2%2
  3. head.style.top2%因爲2%2無效

第三次重複第二次。

使用parseInt從長度中提取數字。

+0

我編輯了代碼,現在它讀取字符串,將其解析爲int,然後完成工作。但在控制檯中它仍然顯示爲NaN,因此它仍然不起作用。 – silicoin

+0

好吧,看起來問題是因爲第一次有'str = head.style.top;',變量'str'只是一個空字符串,因此parseInt不起作用。我所要做的只是在實際使用之前檢查'str'中的空字符串,如果其他人將來有這個小問題的話。 – silicoin

-2

它每次都會運行,但問題是每次迭代都會聲明相同的內容。

在您的if聲明之外移動var lel = head.style.top;

var head = document.getElementById('char_furuta_head'); 

    function anime() { 
     var direction = 1; 
     setInterval(frame, 1000); 

     function frame() { 
      // you need first to check here what units are you using in your css, so you can propely clean/parse the value and convert it to a number. I will consider it to be percentages. 
      var lel = parseInt(head.style.top.replace('%','')); 

      if (direction == 1) {  
        lel += 2; 
        head.style.top = lel + '%'; 
        if(lel == 20) { 
         direction = -1; 
        }; 
      } else { 
        lel -= 2; 
        head.style.top = lel + '%'; 
        if(lel == 0) { 
         direction = 1; 
        }; 
      } 
     } 
    } 

    anime(); 
+0

這沒問題,因爲每次迭代都會從DOM CSS中讀取當前值並添加/減去2%。沒有任何問題。 – Gerfried

+0

如果您沒有嵌入式樣式,問題似乎與'css'有關。你可以從這裏獲得更多細節:http://stackoverflow.com/questions/2664045/how-to-get-an-html-elements-style-values-in-javascript – n1kkou

+0

當你設置一個值時,樣式被設置爲內聯like head.style.top – Gerfried

-1

您的代碼有以下問題:

1)功能動畫()沒有右括號「}」

2)的時間間隔爲1秒 - 不知道你是否真的每秒想移動DIV 2%?

3.)您不能將「2%」+「2%」等百分比加起來。您需要將該字符串轉換爲整數。你可以爲此使用parseInt。

+2

你也不能添加''2px「+」2px「'。 – Quentin

+0

@Quentin - 謝謝你,我糾正了我的答案。 – Gerfried

+0

更正了括號問題,我只是沒有正確複製它。 – silicoin