js sweetalert实现输入验证码并且判断输入的是否为111111,且让其起效
时间: 2024-02-18 08:04:06 浏览: 29
如果你想让这段代码生效,需要确保已经引入了 SweetAlert2 的库文件。可以在页面中添加以下代码引入 SweetAlert2 的 CSS 和 JS 文件:
```html
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/sweetalert2@10.16.6/dist/sweetalert2.min.css">
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@10.16.6/dist/sweetalert2.min.js"></script>
```
同时,你还需要在页面中添加一个按钮或者其他触发弹窗的元素,并在其点击事件中调用弹窗的代码,例如:
```html
<button onclick="showVerificationCode()">验证</button>
```
然后在 JavaScript 中定义 `showVerificationCode()` 函数,并在其中添加弹窗的代码:
```javascript
function showVerificationCode() {
Swal.fire({
title: '请输入验证码:',
input: 'text',
inputAttributes: {
autocapitalize: 'off'
},
showCancelButton: true,
confirmButtonText: '确认',
showLoaderOnConfirm: true,
preConfirm: (code) => {
return new Promise((resolve) => {
setTimeout(() => {
if (code === '111111') {
resolve()
} else {
Swal.showValidationMessage('验证码错误')
}
}, 1000)
})
},
allowOutsideClick: () => !Swal.isLoading()
}).then((result) => {
if (result.value) {
Swal.fire({
title: '验证码输入正确!',
icon: 'success'
})
}
})
}
```
这样,在点击验证按钮时,就会弹出输入验证码的弹窗,并根据输入结果弹出相应的提示框。