Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
¿Cómo puedo usar localStorage para hacer que el navegador recuerde un estado de alternancia de lista de clases para un cambio de tema de modo claro/oscuro?

Estoy trabajando en un sitio web de cartera que tiene un interruptor de tema de modo claro/oscuro. El interruptor funciona, pero no guarda la entrada. Entonces, cuando el usuario actualiza o hace clic en un enlace de navegación, el sitio web vuelve al modo de luz predeterminado. Quiero que recuerde el estado. Sé que tengo que usar localStorage para que funcione, pero parece que no puedo encontrar la manera de hacerlo.

Sitio Web: Www.hermanvulkers.com

Código de cambio de tema de JavaScript:

 button.addEventListener("click", function () { if (document.body.classList.contains("light-theme")) { // Turn light mode off -> dark mode on document.body.classList.toggle("light-theme"); document.getElementById('themeswitcher').innerHTML = `<span>Dark</span><img src="images/moon.png" alt="Choose website theme">`; } else { // Turn dark mode off -> light mode on document.body.classList.toggle("light-theme"); document.getElementById('themeswitcher').innerHTML = `<span>Light</span><img src="images/sunrise.png" alt="Choose website theme"></img>`; } });

Código del botón HTML:

 <button class="themeswitcher" id="themeswitcher"> <span>Dark</span> <img src="images/moon.png" alt="Choose website theme"> </button>

¿Hay alguno capaz de ayudar? ¡Gracias por adelantado!

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

Su código es innecesariamente complejo.

Aquí hay una versión completa

 window.addEventListener("load",function() { const theme = localStorage.getItem("theme"); if (theme) document.body.classList.toggle("light-theme",theme==="light") document.getElementById("themeswitcher").addEventListener("click", function () { const light = document.body.classList.contains("light-theme") this.innerHTML = `<span>${light? 'Dark' : 'light'}</span><img src="images/${light? 'moon' : 'sunrise'}.png" alt="Choose website theme">`; document.body.classList.toggle("light-theme"); localStorage.setItem("theme",light?"dark":"light"); }); });
about 4 years ago · Juan Pablo Isaza Report

0

Puedes agregarlo así:

 button.addEventListener("click", function () { if (document.body.classList.contains("light-theme")) { // Turn light mode off -> dark mode on window.localStorage.setItem('darkmodeTurnedOn', 'true'); document.body.classList.toggle("light-theme"); document.getElementById('themeswitcher').innerHTML = `<span>Dark</span><img src="images/moon.png" alt="Choose website theme">`; } else { // Turn dark mode off -> light mode on document.body.classList.toggle("light-theme"); window.localStorage.setItem('darkmodeTurnedOn', 'false'); document.getElementById('themeswitcher').innerHTML = `<span>Light</span><img src="images/sunrise.png" alt="Choose website theme"></img>`; } });

Además, en la carga inicial de su sitio, debe tener un oyente para activar o desactivar esto, así:

 <body onload="setTheme">

Y en la función setTheme puedes hacer lo siguiente:

 function setTheme(){ if (window.localStorage.getItem('darkmodeTurnedOn') === 'true'){ document.body.classList.remove("light-theme"); } }
about 4 years ago · Juan Pablo Isaza Report

0

Simplemente puede configurar un elemento en localStorage con:

 localStorage.setItem('key', value);

y luego acceder con

 let value = localStorage.getItem('key');

Así que creo que esto debería funcionar:

 button.addEventListener("click", function () { if (document.body.classList.contains("light-theme")) { // Turn light mode off -> dark mode on document.body.classList.toggle("light-theme"); document.getElementById('themeswitcher').innerHTML = `<span>Dark</span><img src="images/moon.png" alt="Choose website theme">`; window.localStorage.setItem('darkMode', 'true'); } else { // Turn dark mode off -> light mode on document.body.classList.toggle("light-theme"); document.getElementById('themeswitcher').innerHTML = `<span>Light</span><img src="images/sunrise.png" alt="Choose website theme"></img>`; window.localStorage.setItem('darkMode', 'false'); } });

Y en algún lugar al comienzo de su código:

 let wasDarkMode = window.localStorage.getItem('darkMode'); if (wasDarkMode) { document.body.classList.toggle("light-theme"); document.getElementById('themeswitcher').innerHTML = `<span>Dark</span><img src="images/moon.png" alt="Choose website theme">`; } else { document.body.classList.toggle("light-theme"); document.getElementById('themeswitcher').innerHTML = `<span>Light</span><img src="images/sunrise.png" alt="Choose website theme"></img>`; }
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!