最近项目在做一个登录页的时候,为了避免用户的多次重复点击登录按钮发送请求,所以我在点击了按钮发送请求后,将设置按钮变灰并禁用,倒计时一段时间后又可重复点击,具体实现如下,有需要的小伙伴可以参考一下。

关键代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>登录页</title>
<script type="text/javascript">
window.onload = _ => {
document.getElementById('btn').onclick = function () {
send(this, 60)
}
}
/**
* 控制 ele 的按钮在指定时间内禁止重复点击
* @param ele 标签对象
* @param time 禁用时间(s)
*/
function send (ele, time) {
if (!time) {
ele.removeAttribute('disabled')
return ele.value = '登录'
}
ele.setAttribute('disabled', true)
ele.value = time + '秒后可以重新登录'
setTimeout(_ => send(ele, --time), 1000)
}
</script>
</head>
<body>
<input type="button" id="btn" value="登录"/>
</body>
</html>