js 实现alert
使用 alert 函数显示消息
在 JavaScript 中,alert 是一个全局函数,用于在浏览器中弹出一个警告对话框。以下是基本用法:
alert("这是一个警告消息");
执行上述代码会在浏览器中弹出一个对话框,显示消息“这是一个警告消息”,用户需要点击“确定”按钮才能关闭对话框。

自定义警告框样式
默认的 alert 对话框样式由浏览器决定,无法直接修改。如果需要自定义样式,可以模拟一个警告框:

function customAlert(message) {
const alertBox = document.createElement("div");
alertBox.style.position = "fixed";
alertBox.style.top = "50%";
alertBox.style.left = "50%";
alertBox.style.transform = "translate(-50%, -50%)";
alertBox.style.padding = "20px";
alertBox.style.background = "white";
alertBox.style.border = "1px solid #ccc";
alertBox.style.borderRadius = "5px";
alertBox.style.boxShadow = "0 0 10px rgba(0, 0, 0, 0.1)";
alertBox.style.zIndex = "1000";
const messageText = document.createElement("p");
messageText.textContent = message;
alertBox.appendChild(messageText);
const closeButton = document.createElement("button");
closeButton.textContent = "确定";
closeButton.style.marginTop = "10px";
closeButton.onclick = function() {
document.body.removeChild(alertBox);
};
alertBox.appendChild(closeButton);
document.body.appendChild(alertBox);
}
customAlert("这是一个自定义警告框");
使用 confirm 替代 alert
如果需要用户确认操作,可以使用 confirm 函数。它会返回一个布尔值,表示用户点击的是“确定”还是“取消”:
const result = confirm("你确定要执行此操作吗?");
if (result) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
使用 prompt 获取用户输入
如果需要用户输入信息,可以使用 prompt 函数:
const userName = prompt("请输入你的名字", "默认名字");
if (userName !== null) {
console.log(`用户输入的名字是: ${userName}`);
}
注意事项
alert、confirm和prompt会阻塞浏览器线程,直到用户关闭对话框。- 在现代 Web 开发中,通常推荐使用自定义模态框(如 Bootstrap Modal 或自定义实现)替代原生弹窗,以提供更好的用户体验和样式控制。






