简体   繁体   中英

How do I fix this (it is supposed to toggle 'toggle')

This is supposed to toggle between off and on with a click but won't go back to on. :(

I have tried true/false statements as well as g--; & g++; (or g-=1; & g+=1; )

    var toggle=true;
    var g = 1;
    draw=function() {
       if (mouseIsPressed&&g===1){
            toggle=true;
            g=2;
       }
       if (mouseIsPressed&&g===2) {
            toggle=false;
            g=1;
       }
       if(toggle===true){
            background(255, 255, 255);
            fill(255, 0, 255);
            text('('+ mouseX + ',' + mouseY+')',mouseX,mouseY);
        }
        if(toggle===false){
            background(255,255,255);
            text('(off)',mouseX,mouseY);
        }
    };

I was expecting it to toggle at a click but it is only staying at the second step.

The second if statement will always be true , because the first one sets g=2 . Here is a simplified example:

 var mouseIsPressed = true; var g = 1; var toggle = false; if (mouseIsPressed && g === 1) { console.log('inside first `if`'); toggle = true; console.log('set toggle =', toggle); g = 2; console.log('set g =', g); } if (mouseIsPressed && g === 2) { console.log('inside second `if`'); toggle = false; console.log('set toggle =', toggle); g = 1; console.log('set g =', g); } 

You can see that both if statements are executed.

You want else if instead:

if (mouseIsPressed && g === 1) {
  toggle = true;
  g = 2;
} else if (mouseIsPressed && g === 2) {
  toggle = false;
  g = 1;
}

However, if you are not actually using g for anything else and just want to toggle the value of toggle , you can just do:

if (mouseIsPressed){
  toggle = !toggle;
}

just add and remove css classes:

 let toggle = false document.addEventListener("click", function(e) { if (toggle) { document.getElementById("main").classList = "on" } else { document.getElementById("main").classList = "off" } const onOff = toggle ? "(off)" : "(on)" document.getElementById("main").innerHTML = onOff + " " + e.clientX + ", " + e.clientY toggle = !toggle }) 
 #main { width: 100px; color: white; height: 100px; } .on { background: blue; } .off { background: red; } 
 <div id="main"></div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM