js实现定时弹出验证
使用 setTimeout 实现基础定时弹窗
创建一个简单的定时弹窗,可以在页面加载后延迟弹出验证窗口:
setTimeout(function() {
if (confirm('需要验证您的身份,是否继续?')) {
console.log('用户通过验证');
} else {
console.log('用户取消验证');
}
}, 5000); // 5秒后弹出
结合模态框的优雅实现
使用自定义模态框替代原生confirm,提升用户体验:
function showVerificationModal() {
const modal = document.createElement('div');
modal.style.cssText = `
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.5); display: flex;
justify-content: center; align-items: center; z-index: 1000;
`;
modal.innerHTML = `
<div style="background: white; padding: 20px; border-radius: 8px;">
<h3>安全验证</h3>
<p>请完成验证以继续操作</p>
<button id="verify-btn">验证</button>
<button id="cancel-btn">取消</button>
</div>
`;
document.body.appendChild(modal);
document.getElementById('verify-btn').addEventListener('click', () => {
document.body.removeChild(modal);
console.log('验证通过');
});
document.getElementById('cancel-btn').addEventListener('click', () => {
document.body.removeChild(modal);
console.log('验证取消');
});
}
setTimeout(showVerificationModal, 10000); // 10秒后弹出
基于用户行为的智能触发
结合用户不活跃状态触发验证,提升安全性:
let idleTimer = null;
const idleTimeout = 300000; // 5分钟
function resetIdleTimer() {
clearTimeout(idleTimer);
idleTimer = setTimeout(() => {
showVerificationModal();
}, idleTimeout);
}
// 监听用户活动
['mousemove', 'keydown', 'scroll'].forEach(event => {
window.addEventListener(event, resetIdleTimer);
});
resetIdleTimer(); // 初始化计时器
添加验证码功能
集成简单验证码验证:
function showCaptchaModal() {
const modal = document.createElement('div');
modal.style.cssText = `
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.5); display: flex;
justify-content: center; align-items: center; z-index: 1000;
`;
const captchaText = Math.random().toString(36).substr(2, 5);
modal.innerHTML = `
<div style="background: white; padding: 20px; border-radius: 8px;">
<h3>安全验证</h3>
<p>请输入下方显示的验证码:</p>
<div style="font-size: 24px; letter-spacing: 3px; margin: 15px 0;">${captchaText}</div>
<input type="text" id="captcha-input" placeholder="输入验证码">
<button id="submit-btn">提交</button>
</div>
`;
document.body.appendChild(modal);
document.getElementById('submit-btn').addEventListener('click', () => {
const input = document.getElementById('captcha-input').value;
if(input === captchaText) {
document.body.removeChild(modal);
console.log('验证码正确');
} else {
alert('验证码错误,请重试');
}
});
}
setTimeout(showCaptchaModal, 15000); // 15秒后弹出
结合本地存储的重复验证
避免频繁弹窗,使用localStorage记录验证状态:
function showStoredVerification() {
const lastVerified = localStorage.getItem('lastVerified');
const now = new Date().getTime();
if(!lastVerified || (now - lastVerified) > 3600000) { // 1小时有效期
if(confirm('需要重新验证您的身份')) {
localStorage.setItem('lastVerified', now);
console.log('验证状态已更新');
}
}
}
setTimeout(showStoredVerification, 20000); // 20秒后检查






