toast.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. // 极简版 Toast - 纯 JS 实现,无依赖
  2. (function () {
  3. // 创建样式
  4. const style = document.createElement("style");
  5. style.textContent = `
  6. .simple-toast {
  7. position: fixed;
  8. top: 50%;
  9. left: 50%;
  10. transform: translate(-50%, -50%);
  11. padding: 10px 20px;
  12. background: rgba(0, 0, 0, 0.8);
  13. color: #fff;
  14. border-radius: 4px;
  15. font-size: 14px;
  16. z-index: 9999;
  17. max-width: 80%;
  18. text-align: center;
  19. animation: toastFade 0.3s;
  20. box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  21. }
  22. @keyframes toastFade {
  23. from { opacity: 0; }
  24. to { opacity: 1; }
  25. }
  26. `;
  27. document.head.appendChild(style);
  28. // Toast 函数
  29. window.$toast = function (message, duration = 2000) {
  30. // 移除已存在的 toast
  31. const existingToast = document.querySelector(".simple-toast");
  32. if (existingToast) {
  33. existingToast.remove();
  34. }
  35. // 创建新 toast
  36. const toast = document.createElement("div");
  37. toast.className = "simple-toast";
  38. toast.textContent = message;
  39. // 点击关闭
  40. toast.addEventListener("click", () => {
  41. toast.remove();
  42. });
  43. // 添加到页面
  44. document.body.appendChild(toast);
  45. // 自动关闭
  46. setTimeout(() => {
  47. if (toast.parentNode) {
  48. toast.remove();
  49. }
  50. }, duration);
  51. return toast;
  52. };
  53. // 添加快捷方法
  54. ["success", "error", "info", "warning"].forEach((type) => {
  55. window.$toast[type] = function (message, duration) {
  56. const toast = window.$toast(message, duration);
  57. // 可以在这里根据 type 设置不同颜色
  58. if (type === "success") toast.style.background = "rgba(76, 175, 80, 0.9)";
  59. if (type === "error") toast.style.background = "rgba(244, 67, 54, 0.9)";
  60. if (type === "warning") toast.style.background = "rgba(255, 152, 0, 0.9)";
  61. return toast;
  62. };
  63. });
  64. })();