在前端开发中,“notice”(通知)通常指用于向用户传达信息的提示或弹窗。虽然 JavaScript 原生没有名为 notice 的函数,但开发者常通过 alert()、自定义模态框等方式实现类似功能。
最基础的方式是使用浏览器内置的 alert() 方法:
// 简单通知
alert("这是一条系统通知!");
为了更好的用户体验和样式控制,我们可以创建一个自定义的 notice 组件:
<div id="customNotice" style="display:none; position:fixed; top:20px; right:20px; background:#3498db; color:white; padding:15px; border-radius:6px; z-index:1000;">
<span id="noticeText"></span>
<button onclick="closeNotice()" style="float:right; background:none; border:none; color:white; cursor:pointer;">×</button>
</div>
<script>
function showNotice(message) {
document.getElementById('noticeText').textContent = message;
document.getElementById('customNotice').style.display = 'block';
}
function closeNotice() {
document.getElementById('customNotice').style.display = 'none';
}
</script>
更现代的做法是让通知在几秒后自动消失:
function showToast(message, duration = 3000) {
const toast = document.createElement('div');
toast.textContent = message;
toast.style.cssText = `
position: fixed;
bottom: 20px;
left: 50%;
transform: translateX(-50%);
background: #2ecc71;
color: white;
padding: 12px 24px;
border-radius: 6px;
z-index: 1000;
box-shadow: 0 4px 8px rgba(0,0,0,0.2);
`;
document.body.appendChild(toast);
setTimeout(() => {
toast.style.opacity = '0';
toast.style.transition = 'opacity 0.5s';
setTimeout(() => document.body.removeChild(toast), 500);
}, duration);
}
“notice” 并非 JavaScript 标准 API,但在实际项目中广泛用于表示用户通知。你可以根据需求选择:
alert()