javascript - 我正在创建的窗口在屏幕周围跳跃,为什么?

标签 javascript

希望我能正确地解释这一点。我是显式使用浏览器对象模型的新手。我的程序应该创建一个新窗口,然后沿屏幕边缘移动该窗口(顺时针)。我相信时间有些不对劲,因为当我运行它时,窗口开始向右移动到屏幕顶部,然后加速到它在各处弹跳的程度。这是我所拥有的:

<html>
<head>
    <script>
        var x = 0;
        var y = 0;
        var moveX = true;
        var moveY = false;
        var aWindow;
        var timer;
        function openWindow(){
            aWindow = window.open("", "", "width=400, height=200");
            aWindow.document.write("This is my new window");
        }

        function closeWindow(){
            if(aWindow){
                aWindow.close();
            }
        }


        function moveWindow(){
            if(aWindow){
                if(moveX){
                    x += 100;
                }
                if(moveY){
                    y += 100;
                }
                if(x == 1200){
                    moveX = false;
                    moveY = true;
                    x *= -1;        //Sets up x so it will move back across the screen backwards
                }
                if(y == 700){
                    moveX = true;
                    moveY = false;
                    y *= -1;        //Sets up y so it will move back up the screen
                }
                aWindow.moveTo(x, y);
                timer = setInterval(moveWindow, 1000)
            }
        }

        function stopMove(){
            clearInterval(timer);
        }
    </script>
</head>

<body>
    <button onclick="openWindow();">Open</button>
    <button onclick="closeWindow();">Close</button>
    <button onclick="moveWindow();">Move</button>
    <button onclick="stopMove();">Stop moving</button>
</body>
</html>

最佳答案

问题是,每次调用 moveWindow 时,它都会设置另一个计时器间隔来运行自己。因此 moveWindow 调用的数量不断增加。

您应该只使用 setInterval 一次,可能在它自己的 startMoving 函数中。

您可以将移动按钮的 onclick="moveWindow()" 替换为 onclick=startMoving() 函数来调用 setInterval 一次

关于javascript - 我正在创建的窗口在屏幕周围跳跃,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55230098/

相关文章:

javascript - 使用 Ajax 自动更新 Highcharts

javascript - 如何使 AngularJS 在 View 之间切换并显示更新列表

javascript - 倍数上的按钮切换文本

javascript - 阻止 JavaScript 关闭窗口

javascript - IntersectionObserver 无法在 Safari 或 iOS 中工作

c# - 如何在 jQuery 函数中使用 Windows Phone 8 C# 列表

javascript - 使用 vuejs 和 axios 显示来自 JSON API 的数据

javascript - 使用 jQuery 读取 JSON 并通过 ID 匹配字段

javascript - 在 Houdini CSS 上创建亮度函数

javascript - 滚动表格的 JQuery 或 Javascript?