如何使用JavaScript创建自定义弹窗替换默认Alert?
替换默认alert为自定义弹窗的实现方案
没问题,我来帮你把默认的alert替换成更美观可控的自定义弹窗,下面分步骤给你讲具体实现:
1. 添加自定义弹窗的HTML结构
首先在你的页面中(比如和sendmail div同级的位置)加入自定义弹窗的HTML,初始设置为隐藏状态:
<!-- 自定义弹窗容器 --> <div id="customAlertModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.5); z-index:9999;"> <div style="background:#fff; width:420px; margin:12% auto; padding:24px; border-radius:8px; text-align:center;"> <h4 id="alertContent" style="margin:0 0 20px 0; color:#333;"></h4> <button id="closeAlertBtn" class="btn btn-primary">确定</button> </div> </div>
2. 编写弹窗控制函数
在你的index.js中添加一个用于显示/关闭自定义弹窗的函数:
// 自定义弹窗控制函数 function showCustomAlert(message) { // 填充弹窗消息内容 document.getElementById('alertContent').textContent = message; // 显示弹窗 document.getElementById('customAlertModal').style.display = 'block'; // 绑定关闭按钮事件 document.getElementById('closeAlertBtn').onclick = function() { document.getElementById('customAlertModal').style.display = 'none'; }; // 点击弹窗背景也关闭(可选功能) window.onclick = function(event) { const modal = document.getElementById('customAlertModal'); if (event.target === modal) { modal.style.display = 'none'; } }; }
3. 修改sendMail函数的回调逻辑
把原来的alert()调用替换成我们刚写的showCustomAlert()函数:
function sendMail(){ console.log(employee_id); var employeeid = employee_id; $.ajax({ url:'http://localhost:8088/JirasTrackingApp/reporter/Reportees/JiraNames/'+employeeid, type:'GET', success: function(Jiranumbers){ // 替换默认成功提示 showCustomAlert("Mail is sent successfully"); }, error: function(Jiranumbers){ // 替换默认失败提示 showCustomAlert("Mail is not sent successfully"); } }); }
可选优化建议
- 如果你的项目已经引入了Bootstrap,可以直接使用Bootstrap的模态框组件,省去自定义样式的工作,样式也更统一。
- 可以给弹窗添加淡入淡出的动画效果,只需要给弹窗容器添加CSS的
transition: opacity 0.3s ease;属性即可提升用户体验。
这样修改后,点击SendMail按钮完成验证后,就会弹出你自定义样式的弹窗,替代浏览器默认的alert框啦~
内容的提问来源于stack exchange,提问作者Ramya




