js 实现alert
使用 alert() 方法
在 JavaScript 中,alert() 是浏览器提供的全局方法,用于显示一个带有指定消息和“确定”按钮的警告框。
alert("这是一个警告消息");
自定义样式或替代方案
原生 alert() 的样式无法直接修改。若需自定义样式或交互,可以使用以下替代方案:

1. 使用 console.log() 输出到控制台

console.log("调试信息");
2. 使用 DOM 创建自定义弹窗
通过 HTML 和 CSS 实现可定制的弹窗:
<div id="customAlert" style="display:none; position:fixed; top:20%; left:30%; background:#fff; padding:20px; border:1px solid #000;">
<p id="alertMessage"></p>
<button onclick="document.getElementById('customAlert').style.display='none'">确定</button>
</div>
<script>
function showCustomAlert(message) {
document.getElementById("alertMessage").innerText = message;
document.getElementById("customAlert").style.display = "block";
}
showCustomAlert("自定义弹窗消息");
</script>
3. 使用第三方库(如 SweetAlert)
引入 SweetAlert2 库实现美观弹窗:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire("标题", "这里是消息内容", "info");
</script>
注意事项
alert()会阻塞浏览器线程,直到用户点击“确定”。- 在 Node.js 环境中无法使用
alert(),需通过console.log()或其他模块实现类似功能。






