JavaScript-淡入淡出功能不起作用



我是JavaScript新手。我在这里的目标是淡出禁区。请检查我的代码,让我知道这里哪里出了问题?当用户单击"淡入淡出"时,框是否应该更改不透明度?我试图定义函数淡入淡出按钮,调用函数并执行淡入淡出切换,但似乎不起作用。

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

opacity样式默认为1,因此添加和删除类是不明显的。因此,我将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>


下面的代码片段演示了在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>

相关内容

最新更新