Soy nuevo en JavaScript. Mi objetivo aquí es desvanecerse dentro y fuera de la caja. Revise mi código y hágame saber qué estoy haciendo mal aquí. Cuando un usuario hace clic en Desvanecer, ¿el cuadro debería cambiar de opacidad? Traté de definir el botón de atenuación de la función y llamar a la función y ejecutar la alternancia de atenuación de entrada y salida, pero parece que no funciona.
<!DOCTYPE html> <html> <head> <title>Watch That Box</title> </head> <style> .fade-in { opacity: 1; } </style> <body> <p>Press the buttons to change the box!</p> <div id="box" style="height:150px; width:150px; background-color:orange; margin:25px;"></div> <button onclick="growbutton()"> Grow </button> <button onclick="fadebutton()"> Fade </button> <button onclick="resetbutton()"> Reset </button> <button onclick="bluebutton()"> Blue </button> <script> const box = document.getElementById("box"); function fadebutton() { box.classList.toggle("fade-in"); } </script> <script src="javascript.js"></script> </body> </html>El estilo de opacity predeterminado es 1 , por lo que agregar y eliminar la clase no se nota. Por lo tanto, actualicé el estilo de opacity a 0.5 .
const box = document.getElementById("box"); const fade = document.getElementById("fade"); /* Click event listener for <button> with id value of "fade" */ fade.addEventListener("click", function() { box.classList.toggle("fade-in"); }); .fade-in { /* The style below has been updated. */ opacity: 0.5; } #box { height:150px; width:150px; background-color:orange; margin:25px; } <body> <p>Press the buttons to change the box!</p> <div id="box"></div> <button id="fade">Fade</button> </body>El fragmento de código a continuación demuestra la implementación de la solución anterior dentro de un archivo HTML.
<!DOCTYPE html> <html> <head> <title>Watch That Box</title> </head> <style> .fade-in { opacity: 0.5; /* The style below has been updated. */ } #box { height:150px; width:150px; background-color:orange; margin:25px; } </style> <body> <p>Press the buttons to change the box!</p> <div id="box"></div> <button id="fade">Fade</button> <script> const box = document.getElementById("box"); const fade = document.getElementById("fade"); /* Click event listener for <button> with id value of "fade" */ fade.addEventListener("click", function() { box.classList.toggle("fade-in"); }); </script> </body> </html>