Hice un botón y agregué un detector de eventos para hacer clic en él. en este momento configuré el siguiente código para JS (la identificación del botón es la siguiente):
next.addEventListener("click", () => { if (AB.style.backgroundColor === "pink") { AB.style.backgroundColor = "red"; } else if (AB.style.backgroundColor === "red") { AB.style.backgroundColor = "orange"; } }); #AB { background-color: pink; } <div id="AB">Words</div> <button id="next">Button</button> Ahora, cuando hago clic en el botón por primera vez, el color cambia de rosa a rojo. Sin embargo, el segundo clic (es decir, la parte else if ) no hace nada. ¿Cómo puedo hacer que el color cambie al hacer clic?
Sí, como sugirió @ggorlen Mire en getComputedStyle().
Pero le dará un valor calculado, que está en formato rgb(,,,) .
Recomiendo usar clases en su lugar.
<!DOCTYPE html> <html> <head> <style type="text/css"> .pink { background-color: pink; } .red { background-color: red; } .orange { background-color: orange; } </style> </head> <body> <div id="AB" class="pink">Words</div> <button id="next">Button</button> </body> <script> next.addEventListener("click", () => { const element = document.getElementById('AB'); if (element.classList.contains('pink')) { element.classList.remove('pink'); element.classList.add('red'); } else if (element.classList.contains('red')) { element.classList.remove('red'); element.classList.add('orange'); } }); </script> </html>El problema aquí es que parece que su div no tiene ningún valor de style.backgroundColor por defecto.
Para enfrentar este problema, puede establecer el valor de backgroundColor dinámicamente cuando se carga el javascript.
AB.style.backgroundColor = "pink" next.addEventListener("click", function () { if (AB.style.backgroundColor === "pink") { AB.style.backgroundColor = "red"; } else if (AB.style.backgroundColor === "red") { AB.style.backgroundColor = "orange"; } }); <div id="AB">Words</div> <button id="next">Button</button>Como comentó ggorlen, puede obtener el estilo usando getComputedStyle() y luego compararlo con la propiedad CSS background-color. Echa un vistazo a getComputedStyle en MDN.
next.addEventListener("click", () => { if (getComputedStyle(AB).getPropertyValue("background-color") === "rgb(255, 192, 203)") { AB.style.backgroundColor = "red"; } else if (AB.style.backgroundColor === "red") { AB.style.backgroundColor = "orange"; } }); #AB { background-color: pink; } <div id="AB">Words</div> <button id="next">Button</button>