js实现提示框
使用原生JavaScript实现提示框
创建基础HTML结构 在HTML文件中添加一个div元素作为提示框容器,默认隐藏:
<div id="customAlert" style="display:none;">
<div class="alert-content">
<span id="alertMessage"></span>
<button id="alertOK">确定</button>
</div>
</div>
添加CSS样式 为提示框添加基本样式:
#customAlert {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
z-index: 9999;
}
.alert-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background: white;
padding: 20px;
border-radius: 5px;
}
JavaScript功能实现 创建显示提示框的函数:
function showAlert(message) {
const alertBox = document.getElementById('customAlert');
const messageElement = document.getElementById('alertMessage');
const okButton = document.getElementById('alertOK');
messageElement.textContent = message;
alertBox.style.display = 'block';
okButton.onclick = function() {
alertBox.style.display = 'none';
};
}
使用第三方库实现提示框
SweetAlert2库 安装SweetAlert2:

npm install sweetalert2
基本使用示例:
import Swal from 'sweetalert2';
Swal.fire({
title: '提示',
text: '这是一个漂亮的提示框',
icon: 'info',
confirmButtonText: '确定'
});
Toastr库 安装Toastr:
npm install toastr
使用示例:

import toastr from 'toastr';
toastr.success('操作成功完成');
toastr.error('发生了一个错误');
高级自定义提示框
可配置的提示框函数 创建更灵活的提示框函数:
function showCustomAlert(options) {
const defaults = {
title: '提示',
message: '',
type: 'info',
confirmText: '确定',
cancelText: '取消',
showCancel: false,
callback: null
};
const config = {...defaults, ...options};
// 创建DOM元素和逻辑...
}
动画效果实现 为提示框添加动画效果:
.alert-content {
animation: fadeIn 0.3s;
}
@keyframes fadeIn {
from { opacity: 0; transform: translate(-50%, -60%); }
to { opacity: 1; transform: translate(-50%, -50%); }
}
浏览器原生提示框
基本alert/prompt/confirm 使用浏览器内置方法:
// 简单提示
alert('这是一个提示');
// 带输入的提示
const name = prompt('请输入您的名字');
// 确认对话框
const isConfirmed = confirm('您确定要删除吗?');
注意事项 原生浏览器对话框会阻塞JavaScript执行,且样式不可自定义,适合简单场景使用。






