Javascript背景颜色切换onclick

时间:2018-01-01 07:36:11

标签: javascript

var bac=document.querySelector("button");

bac.addEventListener("click", function(){
    if (document.body.style.background="white"){
        document.body.style.background="purple";
    }else if(document.body.style.background="purple"){
        document.body.style.background="white";
    }

});

为什么此代码会将背景颜色更改为紫色onclick而不是白色?

3 个答案:

答案 0 :(得分:4)

您正在使用<!-- build:js({.tmp,src/client}) scripts/vendor.js --> <!-- inject:js --> <!-- js files will be automatically insert here --> <!-- endinject --> <!-- endbuild --> <!-- build:js({.tmp,src/client}) scripts/app.js --> <!-- inject:partials --> <!-- angular templates will be automatically converted in js and inserted here --> <!-- endinject --> <!-- endbuild --> 进行相等性比较,但您需要=

&#13;
&#13;
==
&#13;
var bac=document.querySelector("button");
    /* Added the below line because default output of 
       `document.body.style.background` is "" . Therefore we 
        need to initialize it first .
    */
    document.body.style.background="white"; 
    bac.addEventListener("click", function(){
    if (document.body.style.background=="white"){
        document.body.style.background="purple";
    }else if(document.body.style.background=="purple"){
        document.body.style.background="white";
    }

    });
&#13;
&#13;
&#13;

答案 1 :(得分:0)

单个等号( = )用于分配。要比较一个字符串(@SpringBootApplication public class Application extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } public static void main(String[] args) { SpringApplication.run(Application.class, args); } } )与另一个字符串(&#34;白色&#34;),请使用三等号( === )。

document.body.style.background

答案 2 :(得分:0)

使用document.body.style.backgroundColor属性更改背景颜色并使用==进行比较而不是&#34; =&#34;

以下代码已经过测试 js fiddle example

var bac=document.querySelector("button");
document.body.style.backgroundColor="white"; //set default color in js
bac.addEventListener("click", function(){
var color=document.body.style.backgroundColor;
switch(color) {
    case "white":
        document.body.style.backgroundColor="purple";
        break;
    case "purple":
        document.body.style.backgroundColor="white";
        break;
    default:        
}