¿Cómo alternar el estilo de fondo CSS div al hacer clic en el mismo botón?
function changeBg() { var divElem = document.getElementById("change-bg"); divElem.style.backgroundColor = "red"; } body { margin: 0; } #change-bg { /* Extra Text Formatting */ padding: 10px; text-align: center; /* Primary Background Color */ background-color: yellow; } <div id="change-bg"> <h3> Hello World <br/> <button onclick="changeBg();">Change Color</button> </h3> </div>Cambia de color a rojo, pero ¿cómo revertir su color original (amarillo) al hacer clic en el mismo botón?
Echa un vistazo a JSFiddle . Creo que se puede resolver usando If-Else , no puedo implementarlo.
Puede usar classList.toggle para cambiar la cadena del nombre de la clase y volver a cambiarla cuando classList ya tiene el siguiente código
const box = document.querySelector(".bg") const btn = document.querySelector(".btn") btn.addEventListener("click", () => { box.classList.toggle("blue") }) .bg{ background: red; width: 100px; height: 100px; } .blue{ background: blue } <div class="bg"></div> <button class="btn">Toggle it</button>Aquí hay una alternativa con una variable de alternar y la solución if-else mencionada en el OP.
const divElem = document.getElementById("change-bg"); let toggle = true; function changeBg() { divElem.style.backgroundColor = toggle ? 'red' : 'yellow' toggle = !toggle; } body { margin: 0; } #change-bg { padding: 10px; text-align: center; background-color: yellow; } <div id="change-bg"> <h3> Hello World <br/> <button onclick="changeBg();">Change Color</button> </h3> </div>Use este método tal como es :)
function changeBg() { var divElem = document.getElementById("change-bg"); divElem.classList.toggle("change-color"); } body { margin: 0; } #change-bg { /* Extra Text Formatting */ padding: 10px; text-align: center; /* Default Background Color */ background-color: yellow; } .change-color{ background-color: red !important; } <!DOCTYPE html> <head> </head> <body> <div id="change-bg"> <h3> Hello World <br/> <button onclick="changeBg();">Change Color</button> </h3> </div> </body> </html>