2016-11-15 168 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