js实现提示
使用 alert 实现简单提示
alert 是浏览器提供的全局方法,用于显示一个带有消息的对话框。
alert("这是一个提示信息");
缺点:会阻塞页面交互,直到用户点击确认。

使用 console.log 输出调试提示
适用于开发阶段的调试,信息显示在浏览器控制台。
console.log("调试信息");
console.warn("警告信息");
console.error("错误信息");
自定义 DOM 元素提示
通过动态创建 DOM 元素实现更灵活的提示,例如浮动提示框。

function showCustomAlert(message) {
const alertBox = document.createElement("div");
alertBox.style.position = "fixed";
alertBox.style.top = "20px";
alertBox.style.left = "50%";
alertBox.style.transform = "translateX(-50%)";
alertBox.style.padding = "10px 20px";
alertBox.style.background = "#f0f0f0";
alertBox.style.border = "1px solid #ccc";
alertBox.textContent = message;
document.body.appendChild(alertBox);
setTimeout(() => {
document.body.removeChild(alertBox);
}, 3000);
}
showCustomAlert("自定义提示");
使用第三方库(如 Toastr)
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> - 调用方法:
toastr.success("操作成功"); toastr.error("操作失败"); toastr.info("普通提示");
浏览器通知 API(Notification)
需要用户授权,适合桌面端场景。
if (Notification.permission === "granted") {
new Notification("系统通知", { body: "您有一条新消息" });
} else if (Notification.permission !== "denied") {
Notification.requestPermission().then(permission => {
if (permission === "granted") {
new Notification("系统通知", { body: "权限已授予" });
}
});
}
注意事项
- 移动端浏览器可能限制
alert和Notification的使用。 - 自定义提示需考虑样式兼容性和层级问题(如
z-index)。 - 第三方库需权衡体积与功能需求。






