js实现提示框
实现基础提示框(Alert)
使用 alert() 方法可以快速创建一个简单的提示框:
alert("这是一个基础提示框");
自定义确认框(Confirm)
通过 confirm() 实现带确认和取消按钮的对话框,返回布尔值:
const result = confirm("确定要删除吗?");
if (result) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
输入提示框(Prompt)
使用 prompt() 收集用户输入:
const userName = prompt("请输入您的名字", "默认值");
if (userName !== null) {
console.log(`用户输入: ${userName}`);
}
自定义HTML提示框
创建更灵活的DOM元素提示框:
<div id="customModal" style="display:none; position:fixed; top:20%; left:30%; width:40%; background:#fff; padding:20px; border:1px solid #000; z-index:1000;">
<p>自定义提示内容</p>
<button onclick="document.getElementById('customModal').style.display='none'">关闭</button>
</div>
<script>
function showCustomModal() {
document.getElementById('customModal').style.display = 'block';
}
</script>
使用第三方库(SweetAlert)
通过引入SweetAlert2库实现美观提示框:
// 需先引入SweetAlert2库
Swal.fire({
title: '提示',
text: '操作成功完成',
icon: 'success',
confirmButtonText: '确定'
});
定时关闭提示框
实现自动消失的提示框:
function showTemporaryAlert(message, duration) {
const alertBox = document.createElement('div');
alertBox.textContent = message;
alertBox.style.position = 'fixed';
alertBox.style.bottom = '20px';
alertBox.style.right = '20px';
alertBox.style.padding = '10px';
alertBox.style.background = '#4CAF50';
alertBox.style.color = 'white';
document.body.appendChild(alertBox);
setTimeout(() => {
document.body.removeChild(alertBox);
}, duration);
}






