Estoy aprendiendo a crear sitios web. Quiero construir un conmutador de temas simple con HTML/CSS/JavaScript. He hecho la parte de cambio de tema, pero quiero cambiar la imagen en el botón cuando lo presiono.
Aquí está mi foto de la luna: ( https://www.svgrepo.com/svg/6390/moon ) y aquí está mi foto del sol: ( https://www.svgrepo.com/svg/304624/sun-light-theme ).
Aquí está mi código:
const btn = document.querySelector('.btn_theme'); btn.addEventListener('click', function() { document.body.classList.toggle('dark_theme'); }); body { background-color: white; color: black; font-family: "Trebuchet MS", Helvetica, sans-serif; font-size: 16pt; font-weight: normal; } body.dark_theme { background-color: #2F3136; color: white; font-size: 16pt; font-weight: normal; font-family: "Trebuchet MS", Helvetica, sans-serif; } .container { width: 100px; height: 55px; background-color: #2F3136; color: white; text-align: center; border-radius: 10px; position: absolute; display: flex; align-items: center; } .btn_theme { text-align: center; width: 90px; height: 45px; background-color: white; margin: 0; padding: 0; border: 0; left: 5px; border-radius: 8px; position: relative; transition: all .15s linear; -webkit-transition: all .15s linear; -moz-transition: all .15s linear; align-items: center; } button:hover { background-color: #2f3647; transition: all 0.15s linear; -webkit-transition: all 0.15s linear; -moz-transition: all 0.15s linear; } <p>text</p> <div class="container"> <button class="btn_theme" id="btn_theme"><img src="../imgs/солнце.svg" /></button> </div>Hay un par de maneras de lograr esto.
Una forma es simplemente deshacerse de la etiqueta img y cambiar la imagen de fondo del botón.
const btn = document.querySelector('.btn_theme'); btn.addEventListener('click', function() { document.body.classList.toggle('dark_theme'); }); .btn_theme { background: url('https://www.svgrepo.com/show/304624/sun-light-theme.svg'); text-align: center; width: 40px; height: 40px; background-color: white; margin: 0; padding: 0; border: 0; left: 5px; border-radius: 8px; position: relative; transition: all .15s linear; -webkit-transition: all .15s linear; -moz-transition: all .15s linear; align-items: center; } button:hover { background-color: #2f3647; transition: all 0.15s linear; -webkit-transition: all 0.15s linear; -moz-transition: all 0.15s linear; } .dark_theme { background: #ffaaff } .dark_theme .btn_theme { background: url('https://www.svgrepo.com/show/6390/moon.svg'); } <button class="btn_theme" id="btn_theme"></button>Otra solución es usar un atributo de datos para almacenar el estado actual y cambiar el valor src de la etiqueta img.
const btn = document.querySelector('.btn_theme'); const icon = btn.querySelector('img'); btn.addEventListener('click', function() { document.body.classList.toggle('dark_theme'); if (icon.dataset.theme == "light") { icon.dataset.theme = "dark"; icon.src = "https://www.svgrepo.com/show/6390/moon.svg"; } else { icon.dataset.theme = "light"; icon.src = "https://www.svgrepo.com/show/304624/sun-light-theme.svg"; } }); .btn_theme { text-align: center; width: 40px; height: 40px; background-color: white; margin: 0; padding: 0; border: 0; left: 5px; border-radius: 8px; position: relative; transition: all .15s linear; -webkit-transition: all .15s linear; -moz-transition: all .15s linear; align-items: center; } button:hover { background-color: #2f3647; transition: all 0.15s linear; -webkit-transition: all 0.15s linear; -moz-transition: all 0.15s linear; } .dark_theme { background: #ffaaff } <button class="btn_theme" id="btn_theme"><img class="icon" data-theme="light" src="https://www.svgrepo.com/show/304624/sun-light-theme.svg"></button>Debe actualizar el atributo src de su imagen usando setAttribute() .
Podrías usar la aritmética modular para cambiar entre imágenes. Esto funcionaría para la cantidad de imágenes que desee tener. Sin embargo, no es necesario para dos imágenes, ya que solo podría usar un valor booleano. Sin embargo, aquí cómo podría hacerlo usando la operación de módulo .
// All the pictures we want to switch between const pics = [ "https://dummyimage.com/50x50/000/fff", "https://dummyimage.com/50x50/dddddd/000", // "https://dummyimage.com/50x50/d420d4/000" // comment this out for a third pic ] let curPicIdx = 0; window.addEventListener("DOMContentLoaded", e => { // when the page has loaded set the first picture const button = document.getElementById("mybutton"); const img = document.getElementById("myimage"); img.setAttribute("src", pics[curPicIdx]) // whenever we click on the button change the picture to the next one button.addEventListener("click", e => { // calculate the index of the next picture using modular arithmetic curPicIdx = (curPicIdx + 1) % pics.length; console.log(`Setting pic ${curPicIdx}`); // set the next picture using the calculated index img.setAttribute("src", pics[curPicIdx]); }) }) <button id="mybutton"><img id="myimage"/>Si desea tener tres imágenes, simplemente agregue otra URL dentro de la matriz y cambiará entre las tres imágenes.
En general, hay muchas formas de incrustar imágenes en los botones. Es posible que desee echar un vistazo a este hilo .