Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
201 views
in Technique[技术] by (71.8m points)

javascript - Change background colour on button click toggleable

I'm trying to make a toggleable button with the label class "Toggle" change the background of the website on click.

My html is:

<label class="Toggle" id="Toggle-bg" onclick="Togglebg()>
<input type="Checkbox">
<span class="Slider Rounded"></span>
</label>
<p id="Toggle-p">Toggle background</p>

and I would like to add this CSS to the document when it is clicked:

.Background{background: linear-gradient(45deg,lightblue,lightgreen,yellow,orange)}

I'd like it to be toggleable but load the page untoggled, thanks!

Javascript or jquery is fine.

question from:https://stackoverflow.com/questions/65848920/change-background-colour-on-button-click-toggleable

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use a boolean variable for the toggle mechanism.

let togg = false;

document.getElementById("inp").addEventListener("click", Togglebg);

function Togglebg() {
  if (togg) {
    console.log(togg);
    document.getElementById("Toggle-p").style.background = "white";
    togg = false;
  } else {
      console.log(togg);

    togg = true;
    document.getElementById("Toggle-p").style.background = "linear-gradient(45deg, lightblue, lightgreen, yellow, orange";
  }
}
.Background {
  background: linear-gradient(45deg, lightblue, lightgreen, yellow, orange)
}
<label class="Toggle" id="Toggle-bg"> <input id="inp" type="Checkbox">
<span class="Slider Rounded"></span>
</label>
<p id="Toggle-p">Toggle background</p>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...