// 极简版 Toast - 纯 JS 实现,无依赖 (function () { // 创建样式 const style = document.createElement("style"); style.textContent = ` .simple-toast { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); padding: 10px 20px; background: rgba(0, 0, 0, 0.8); color: #fff; border-radius: 4px; font-size: 14px; z-index: 9999; max-width: 80%; text-align: center; animation: toastFade 0.3s; box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2); } @keyframes toastFade { from { opacity: 0; } to { opacity: 1; } } `; document.head.appendChild(style); // Toast 函数 window.$toast = function (message, duration = 2000) { // 移除已存在的 toast const existingToast = document.querySelector(".simple-toast"); if (existingToast) { existingToast.remove(); } // 创建新 toast const toast = document.createElement("div"); toast.className = "simple-toast"; toast.textContent = message; // 点击关闭 toast.addEventListener("click", () => { toast.remove(); }); // 添加到页面 document.body.appendChild(toast); // 自动关闭 setTimeout(() => { if (toast.parentNode) { toast.remove(); } }, duration); return toast; }; // 添加快捷方法 ["success", "error", "info", "warning"].forEach((type) => { window.$toast[type] = function (message, duration) { const toast = window.$toast(message, duration); // 可以在这里根据 type 设置不同颜色 if (type === "success") toast.style.background = "rgba(76, 175, 80, 0.9)"; if (type === "error") toast.style.background = "rgba(244, 67, 54, 0.9)"; if (type === "warning") toast.style.background = "rgba(255, 152, 0, 0.9)"; return toast; }; }); })();