替换按钮为5秒倒计时:页面加载后自动执行JS显示隐藏函数
解决方案:移除按钮并实现5秒倒计时自动执行元素切换
以下是修改后的完整代码,实现页面加载后启动5秒倒计时,结束后自动隐藏myDIV并显示myDIVS:
<!DOCTYPE html> <head> <link rel="stylesheet" href="css/app.min.css" /> <title> Test </title> <style> .myDIV{ background-color: aqua; margin: 30px; padding: 50px 30px; } .myDIVS{ background-color: green; margin: 30px; padding: 50px 30px; display: none; } #countdown { margin: 30px; font-size: 18px; color: #333; } </style> </head> <body> <div id="countdown">倒计时:5秒</div> <div id="myDIV" class="myDIV"> Initializing Hide </div> <div id="myDIVS" class="myDIVS"> Hide Successful </div> <script type="text/javascript"> function myFunction(){ var target = document.getElementById("myDIV"); var show = document.getElementById("myDIVS"); // 直接隐藏目标元素,显示成功元素 target.style.display = "none"; show.style.display = "block"; // 隐藏倒计时提示 document.getElementById("countdown").style.display = "none"; } // 页面加载完成后启动倒计时 document.addEventListener('DOMContentLoaded', function() { let countdown = 5; const countdownEl = document.getElementById('countdown'); // 每秒更新倒计时显示 const timer = setInterval(() => { countdown--; countdownEl.textContent = `倒计时:${countdown}秒`; if(countdown <= 0) { clearInterval(timer); myFunction(); } }, 1000); }); </script> </body> </html>
关键修改说明:
- 移除按钮:直接删除原代码中的
<button>元素 - 修正函数逻辑:原
myFunction里的if条件是错误的赋值操作(=),现在简化为直接设置元素显示状态,无需冗余判断 - 添加倒计时功能:
- 新增
countdown元素显示剩余时间,提升用户体验 - 用
DOMContentLoaded事件确保DOM加载完成后执行逻辑,避免找不到元素的问题 - 通过
setInterval每秒更新倒计时数字,倒计时结束后清除定时器并调用myFunction
- 新增
内容的提问来源于stack exchange,提问作者Adewole Solomon
相关产品推荐
相关产品推荐

