简体   繁体   English

JavaScript - 淡入和淡出 function 不工作

[英]JavaScript - Fade in and Fade out function not working

I'm new to JavaScript.我是 JavaScript 的新手。 My goal here is fade in and out the box.我的目标是淡入淡出盒子。 Please review my code and let me know what am doing wrong here?请查看我的代码并让我知道这里做错了什么? When a user clicks Fade, the box should change opacity?当用户单击 Fade 时,该框应更改不透明度? I tried to define function fade button and call the function and execute the toggle fade in and out, but it appears to be not working.我试图定义 function 淡入淡出按钮并调用 function 并执行切换淡入和淡出,但它似乎不起作用。

 <.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>

The opacity style defaults to 1 so adding and removing the class is unnoticeable. opacity样式默认为1 ,因此添加和删除 class 是不明显的。 Therefore I updated the opacity style to 0.5 .因此我将opacity样式更新为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>


The code snippet below demonstrates the implementation of the above solution within an HTML file.下面的代码片段演示了在 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM