【问题标题】:javascript alert and halting executionjavascript警报和停止执行
【发布时间】:2016-12-06 15:51:31
【问题描述】:

这里我们有一个简单的练习 javascript 游戏,它有一个有效的 HTML 颜色列表,它在页面加载时选择一个随机颜色,当你输入时它会根据你的输入要求你猜测并给你提示正确的颜色,它将背景颜色更改为答案的颜色。

当您输入中奖答案时,您会收到一条提示,告诉您您中奖了,由于某种原因,只有当屏幕上出现提示时我按下确定后,背景颜色才会发生变化,即使声明更改了bg 颜色在警报之前。

我的问题是: (1) 为什么我关闭弹窗后背景颜色会发生变化? (2)在屏幕上出现警报之前让BG颜色改变的正确方法是什么?

function do_game() {
                var colors = ["aqua", "beige", "deeppink" , "coral",  "honeydew", "lime", "gainsboro","rebeccapurple","peru","tan"].sort();
                var answer = colors[Math.floor((Math.random() * colors.length))];
                var finished = 0;
                var numberOfGuesses = 0;
                var myBody=document.getElementsByTagName("body")[0];


                console.log(answer);
                while(!finished){


                var input = prompt('I am thinking of one of these colors \n\n' + colors + '\n\n what color am i thinking of? ' );
                if(input === null) 
                    finished = 1; 
                else{
                    numberOfGuesses++;
                    checkGuess(input);

                    if(input === answer){
                        myBody.style.background=answer;
                        finished = 1;
                        alert('You are right! \n you took ' + numberOfGuesses + ' Guesses!');

                    }
                }

            }

            function checkGuess(input){
                if(colors.indexOf(input) === -1){
                    //does not recognize input
                    alert('I don’t recognize that color!');
                }else if(input > answer){
                    //alphabetically higher
                    alert('Your input is alphabetically higher than mine!');
                }else if(input < answer){
                    //alphabatially lower
                    alert('Your input is alphabetically lower than mine!');
                }
            }
        }

【问题讨论】:

  • 不要使用alert。正如您所见,它正在阻塞,除了不使用它之外,没有其他方法可以避免。
  • 附带说明,这似乎是特定于浏览器的。 Firefox 在我关闭警报之前重新绘制,但 Chrome 之后重新绘制。
  • @andi 哈哈,我试过 chrome 和 safari,所以我错误地认为它是通用的,谢谢。

标签: javascript html


【解决方案1】:

在更新 DOM 的函数完成运行之前,浏览器不会重新绘制屏幕。

alert 正在阻塞,因此会阻止该函数继续运行,直到您单击“确定”。

alert放到另一个函数中,使用setTimeout以非阻塞方式调用。

document.body.style.background = "blue";
setTimeout(function() {
  alert("Hello");
});

【讨论】:

    猜你喜欢
    • 2013-09-10
    • 1970-01-01
    • 1970-01-01
    • 2012-07-24
    • 1970-01-01
    • 2011-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多