js实现提示框
使用 alert() 方法实现基础提示框
alert() 是浏览器内置的全局方法,用于显示简单的文本提示框。
alert('这是一个基础提示框');
使用 confirm() 方法实现确认提示框
confirm() 方法显示一个带有确定和取消按钮的对话框,返回布尔值。
const result = confirm('确定要删除吗?');
if (result) {
console.log('用户点击了确定');
} else {
console.log('用户点击了取消');
}
使用 prompt() 方法实现输入提示框
prompt() 方法显示一个带有输入框的对话框,返回用户输入的字符串。
const name = prompt('请输入您的名字', '默认值');
if (name !== null) {
console.log(`用户输入的名字是:${name}`);
}
自定义HTML提示框
通过HTML和CSS创建更灵活的提示框。
<div id="customAlert" style="display:none; position:fixed; top:50%; left:50%; transform:translate(-50%,-50%); background:white; padding:20px; border:1px solid #ccc; z-index:1000;">
<p id="alertMessage"></p>
<button onclick="hideAlert()">确定</button>
</div>
<script>
function showAlert(message) {
document.getElementById('alertMessage').textContent = message;
document.getElementById('customAlert').style.display = 'block';
}
function hideAlert() {
document.getElementById('customAlert').style.display = 'none';
}
</script>
使用第三方库实现高级提示框
SweetAlert2库提供了美观且功能丰富的提示框。
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
title: '提示',
text: '这是一个漂亮的提示框',
icon: 'success',
confirmButtonText: '确定'
});
</script>
实现Toast提示框
创建短暂显示的轻量级提示。

function showToast(message) {
const toast = document.createElement('div');
toast.textContent = message;
toast.style.position = 'fixed';
toast.style.bottom = '20px';
toast.style.right = '20px';
toast.style.padding = '10px 20px';
toast.style.background = '#333';
toast.style.color = 'white';
toast.style.borderRadius = '5px';
document.body.appendChild(toast);
setTimeout(() => {
document.body.removeChild(toast);
}, 3000);
}






