js 实现msgbox
实现基本的MsgBox功能
在JavaScript中模拟MsgBox(消息框)可以通过原生alert()、confirm()或prompt()实现,或自定义模态对话框:
// 原生alert实现
alert("这是一个提示消息");
// 带确认/取消的对话框
const isConfirmed = confirm("确认执行此操作吗?");
// 带输入框的对话框
const userInput = prompt("请输入内容:");
自定义MsgBox组件
通过HTML/CSS创建更灵活的自定义消息框:
<div id="msgBox" class="msgbox-hidden">
<div class="msgbox-content">
<p id="msgText"></p>
<button id="msgConfirm">确定</button>
</div>
</div>
<style>
.msgbox-hidden { display: none; }
.msgbox-content {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background: white;
box-shadow: 0 0 10px rgba(0,0,0,0.5);
}
</style>
<script>
function showMsgBox(message, callback) {
const msgBox = document.getElementById('msgBox');
document.getElementById('msgText').textContent = message;
msgBox.style.display = 'block';
document.getElementById('msgConfirm').onclick = function() {
msgBox.style.display = 'none';
if(callback) callback(true);
};
}
</script>
使用第三方库
对于更复杂的需求,可以使用现成的UI库:
// 使用SweetAlert2库
Swal.fire({
title: '提示',
text: '操作成功完成',
icon: 'success'
});
// 使用Bootstrap模态框
$('#myModal').modal('show');
异步MsgBox实现
结合Promise实现异步消息框:
function asyncMsgBox(message) {
return new Promise((resolve) => {
showMsgBox(message, resolve);
});
}
// 使用示例
async function process() {
await asyncMsgBox("请确认操作");
console.log("用户已确认");
}
增强型MsgBox功能
扩展自定义消息框支持更多选项:

function showAdvancedMsgBox(options) {
const { title, content, buttons } = options;
// 创建动态DOM元素
// 根据buttons数组生成按钮
// 返回Promise等待用户交互
}
// 调用示例
showAdvancedMsgBox({
title: "警告",
content: "确定要删除吗?",
buttons: [
{ text: "取消", value: false },
{ text: "确定", value: true }
]
}).then(result => {
console.log("用户选择:", result);
});






