JavaScript动画每次迭代时元素的变量错误 "pos"

标签 javascript html css

以下 JavaScript 中包含云图像的元素的动画的逻辑错误到底是什么?我认为“pos”变量似乎在每次迭代中都偏离了方向,而且我无法弄清楚每次迭代时云图像的运动如何变得越来越疯狂。

//CSS:
#container{
               background-color : #defffc;
               width : 100%;
               height : 100%;
               position : relative;
            }

#clouds{
            position : absolute;
            width : 300px;
            height : 200px;
            opacity : 0.3;
        }

//Body: 
<p><button type = "button" onclick = "animateCloud()">Move Cloud</button></p>
    <div id = "container">
        <div id = "cloudy">
            <img src ="cloudy.png" id = "clouds"></img>
        </div>
    </div>

//Script: 
<script>
        function animateCloud(){
            var pos = 0;
            var cloudElement = document.getElementById("clouds");
            var id = setInterval(motion, 5);

            function motion(){
                if(pos==1000){
                    //clearInterval(id);
                    id = setInterval(remotion, 5, pos);
                }
                else{
                        pos++;
                        cloudElement.style.left = pos + 'px';
                        cloudElement.style.right = pos + 'px';
                    }
                }

                function remotion(){
                alert(pos);
                    if(pos==0){
                            id = setInterval(motion, 5, pos);
                    }
                    else{
                            pos--;
                            cloudElement.style.right = pos + 'px';
                            cloudElement.style.left = pos + 'px';
                    }
                }
            }
</script>

最佳答案

通过使用setInterval,您告诉 JavaScript 每 n 毫秒重复一次该函数,因此使用间隔调用创建更多间隔的函数实际上会更频繁地调用您的位置更改。

我建议你看看setTimeout()超过setInterval()以确保您不会重复创建更多间隔。

编辑:再次查看代码后,保留 clearInterval()并记住将其也放入您的 remotion 基本案例中;否则,您将开始以指数方式创建更多间隔,就像我上面提到的那样。

关于JavaScript动画每次迭代时元素的变量错误 "pos",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42788077/

相关文章:

javascript - JQuery 字符串包含检查

javascript - BigCommerce 模板自定义字段

javascript - 让javascript使用它所在的目录

jquery - 为什么我无法通过 JQuery 移动图像?

html - 二维数组中的 SelectedIndex

javascript - 悬停淡入淡出不适用于砌体 CSS

javascript - 使用 javascript 或 ajax 弹出窗口显示所选选项

jquery - 删除下一个元素 - jquery

css - 为什么这个用于动画 SVG 字体大小的选择器工作不一致?

html - 为什么李:focus is not working on display or visibility?