Javascript setInterval()只运行一次该函数

时间:2016-11-15 19:21:45

标签: javascript css

我有这个代码,我试图动画其中一个div。 div应该向下移动,然后降低20%后应该开始上升,然后再下降等等。

问题似乎是代码只运行一次。这意味着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; }; 
        }
    }
}

3 个答案:

答案 0 :(得分: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%
  4. 第二次:

    1. lel2%
    2. lel2%2
    3. head.style.top2%,因为2%2无效
    4. 第三次重复第二次。

      使用parseInt从长度中提取数字。

答案 1 :(得分:-1)

您的代码存在以下问题:

1。)function anime()没有右括号“}”

2。)间隔为1秒 - 不确定你是否真的希望每秒将DIV移动2%?

3。)你不能加上像“2%”+“2%”这样的百分比。您需要将字符串转换为整数。您可以使用parseInt。

答案 2 :(得分:-2)

它每次运行,但问题是你在每次迭代时声明相同的事情。

var lel = head.style.top;移到if声明之外。

    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();
相关问题