button - 执行加载按钮几秒钟
问题描述
我自己设计了一个加载按钮。如果用户点击一个按钮,加载按钮将显示几秒钟,然后在再次点击该按钮之前不再显示。
此代码显示了工作原理的示例。
HTML:
<div id="loader" style="display:none"></div>
<button class="button" onclick="load()">Loading Button</button>
CSS:
#loader {
position: absolute;
left: 50%;
top: 50%;
z-index: 1;
width: 150px;
height: 150px;
margin: -75px 0 0 -75px;
border: 16px solid #f3f3f3;
border-radius: 50%;
border-top: 16px solid #3498db;
width: 120px;
height: 120px;
-webkit-animation: spin 2s linear infinite;
animation: spin 2s linear infinite;
}
@-webkit-keyframes spin {
0% { -webkit-transform: rotate(0deg); }
100% { -webkit-transform: rotate(360deg); }
}
@keyframes spin {
0% { transform: rotate(0deg); }
100% { transform: rotate(360deg); }
}
JS
function load() {
document.getElementById("loader").style.display = "block";
setTimeout(stop(), 5000)
}
function stop() {
document.getElementById("loader").style.display = "none";
}
我的问题是加载按钮没有被调用,但从未显示。我猜这是因为页面上的元素在运行完 js 函数后会刷新,所以只处理最后一个关于“loader”-ID 的命令。
有谁知道也考虑第一个命令的方法?
谢谢你的帮助,
博辛加
解决方案
function load() {
document.getElementById("loader").style.display = "block";
setTimeout(stop(), 5000)
}
问题是 setTimeout 将立即调用停止功能,并且您的加载程序将永远不会显示。
function load() {
document.getElementById("loader").style.display = "block";
setTimeout(function(){
document.getElementById("loader").style.display = "none"; }, 3000);
}
在这种情况下,您只能调用一个函数,这将起作用
https://stackblitz.com/edit/js-yyokfc?file=index.html 工作示例
如果您使用 XMLHttpRequest 将 style.display = "block" 设置为微调器的默认状态,并在请求函数中调用停止函数
let request = new XMLHttpRequest();
request.open('GET', "" true);
// This will be called after the response is received
request.onload = function () {
// stop spinner
stop();
// do stuff
}
request.send();
推荐阅读
- python - 有没有一种快速的方法可以将 4D 数组的一个轴乘以与该轴相同长度的向量中的元素?
- c# - 使用投影在 Automapper 配置文件中进行本地化
- python - 将 json 文件从文件夹转换为 csv 格式
- python - 如何在 AWS Lambda 中读取上传的 excel 文件?
- docker - 有没有办法阻止 docker swarm leave --force 删除当前正在运行的容器的端口重定向
- node.js - Laravel 跳过安装并且无法扫描里面的类
- vba - 可见,不可见的按钮形状 vba
- kubernetes - 为什么我的永久性磁盘无法挂载到我的 pod?
- java - 如何在列表中计算相似的id对象并在recyclerview中显示?
- aws-api-gateway - 通过无服务器框架为 AWS API Gateway 设置响应模型