js实现实现提醒
使用 JavaScript 实现提醒功能
JavaScript 提供了多种方式来实现提醒功能,包括浏览器原生弹窗、桌面通知(Notification API)以及定时提醒(setTimeout/setInterval)。以下是几种常见的实现方法:
浏览器原生弹窗提醒
使用 alert、confirm 或 prompt 方法可以快速实现简单的弹窗提醒:
alert('这是一个提醒消息!'); // 普通弹窗
confirm('确定要执行此操作吗?'); // 带确认/取消的弹窗
prompt('请输入内容:', '默认值'); // 带输入框的弹窗
桌面通知(Notification API)
现代浏览器支持 Notification API,可以在用户桌面显示通知:
// 请求通知权限
if (Notification.permission !== 'granted') {
Notification.requestPermission().then(permission => {
if (permission === 'granted') {
new Notification('提醒标题', {
body: '提醒内容',
icon: 'icon.png'
});
}
});
} else {
new Notification('提醒标题', {
body: '提醒内容',
icon: 'icon.png'
});
}
定时提醒
使用 setTimeout 或 setInterval 可以实现定时提醒:
// 单次定时提醒
setTimeout(() => {
alert('5秒后的提醒!');
}, 5000);
// 重复提醒
const reminder = setInterval(() => {
alert('每分钟提醒一次!');
}, 60000);
// 清除定时器
// clearInterval(reminder);
结合页面内提醒
可以通过 DOM 操作在页面内显示提醒:
function showInlineReminder(message) {
const reminder = document.createElement('div');
reminder.style.position = 'fixed';
reminder.style.bottom = '20px';
reminder.style.right = '20px';
reminder.style.padding = '10px';
reminder.style.background = '#f0f0f0';
reminder.style.border = '1px solid #ccc';
reminder.style.borderRadius = '5px';
reminder.textContent = message;
document.body.appendChild(reminder);
setTimeout(() => {
reminder.remove();
}, 3000);
}
showInlineReminder('这是一个页面内提醒!');
使用第三方库
对于更复杂的提醒功能,可以使用第三方库如:
- Toastr:简单的 toast 通知
- SweetAlert2:美观的弹窗
- Noty:功能丰富的通知库
示例使用 Toastr:

<link href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css" rel="stylesheet">
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script>
toastr.success('操作成功!');
toastr.error('发生错误!');
toastr.info('这是一个信息提醒');
toastr.warning('警告信息');
</script>






