我想更改页面背景颜色,但它并不像我在Chrome中所期望的那样工作

时间:2018-05-24 06:29:18

标签: javascript html css

我是一名新的JavaScript学习者,我想更改页面的背景颜色,所以我在下面写了一页:



<button onclick="change_color()">change color</button>
&#13;
pod deintegrate  
pod install
&#13;
&#13;
&#13;

我希望该功能应该将背景颜色改为绿色,然后显示弹出窗口,然后将背景颜色更改为蓝色。但它在Chrome中运行方式不同,页面在弹出窗口之前不会变为绿色,它只会变为蓝色,我不会看到更改为绿色的过程。 如果我通过Edge或Firefox打开该页面,它运行良好,但如果我通过Chrome 67.0.3396.40或Chrome 66.0.3359.170打开该页面,则该页面在弹出窗口之前不会变为绿色。为什么呢?

3 个答案:

答案 0 :(得分:2)

<!DOCTYPE html>

<head>
    <meta charset="utf-8">
    <title>666</title>
    <script type="text/javascript" charset="utf-8">
    function change_color() {
     console.log('6666');
     document.body.style.backgroundColor = "green";
     setTimeout(function(){alert("the color has changed to green!"); }, 5);
     console.log('6666');
     setTimeout(function(){document.body.style.backgroundColor = "blue"; }, 5);
}
    </script>
</head>

<body>
    <button type="button" onclick="change_color()">change color</button>
</body>

</html>

这些是UI阻止事件。您可以设置setTimeout以使其正常工作

function change_color() {
     console.log('6666');
     document.body.style.backgroundColor = "green";
     setTimeout(function(){alert("the color has changed to green!"); }, 5);
     console.log('6666');
     setTimeout(function(){document.body.style.backgroundColor = "blue"; }, 5);
}

答案 1 :(得分:2)

alert不需要触发DOM重新呈现,在Chrome中也不是这样(与其他浏览器不同)。要查看中间更改,可以使用超时在警报之前插入延迟。 DOM将在那个时候被重新渲染。

function change_color() {
    console.log('6666');
    document.body.style.backgroundColor = "green";
    setTimeout(() => {
        alert("the color has changed to green!");
        console.log('6666');
        document.body.style.backgroundColor = "blue";
    });
}
<button type="button" onclick="change_color()">change color</button>

答案 2 :(得分:0)

你需要一个if else,并用css为你的身体设置一个默认的背景颜色。

<!DOCTYPE html>

<head>
<meta charset="utf-8">
<title>666</title>
<script type="text/javascript" charset="utf-8">
function change_color() {
if(document.body.style.backgroundColor == "blue"){
    console.log('6666');
    document.body.style.backgroundColor = "green";
    alert("the color has changed to green!");
} else { 
    console.log('6666');
    document.body.style.backgroundColor = "blue";
}}
</script>
</head>

<body style="background-color:blue;">
<button type="button" onclick="change_color();">change color</button>
</body>

</html>