toast.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. /**
  2. * H5版本的Toast提示工具
  3. */
  4. // Toast管理器
  5. const toastManager = {
  6. toastElement: null,
  7. toastTimer: null,
  8. // 显示Toast
  9. show(message, duration = 3000, type = 'info') {
  10. // 清除之前的Toast
  11. this.hide()
  12. // 创建Toast元素
  13. this.toastElement = document.createElement('div')
  14. this.toastElement.className = `h5-toast h5-toast-${type}`
  15. this.toastElement.textContent = message
  16. // 添加样式(如果还没有添加)
  17. if (!document.getElementById('h5-toast-style')) {
  18. const style = document.createElement('style')
  19. style.id = 'h5-toast-style'
  20. style.textContent = `
  21. .h5-toast {
  22. position: fixed;
  23. top: 50%;
  24. left: 50%;
  25. transform: translate(-50%, -50%);
  26. padding: 12px 20px;
  27. border-radius: 6px;
  28. font-size: 14px;
  29. z-index: 10001;
  30. max-width: 80%;
  31. text-align: center;
  32. opacity: 0;
  33. transition: opacity 0.3s ease;
  34. }
  35. .h5-toast.show {
  36. opacity: 1;
  37. }
  38. .h5-toast-info {
  39. background: rgba(0, 0, 0, 0.8);
  40. color: white;
  41. }
  42. .h5-toast-success {
  43. background: rgba(40, 167, 69, 0.9);
  44. color: white;
  45. }
  46. .h5-toast-warning {
  47. background: rgba(255, 193, 7, 0.9);
  48. color: #212529;
  49. }
  50. .h5-toast-error {
  51. background: rgba(220, 53, 69, 0.9);
  52. color: white;
  53. }
  54. `
  55. document.head.appendChild(style)
  56. }
  57. // 添加到页面
  58. document.body.appendChild(this.toastElement)
  59. // 显示动画
  60. setTimeout(() => {
  61. this.toastElement.classList.add('show')
  62. }, 10)
  63. // 自动隐藏
  64. this.toastTimer = setTimeout(() => {
  65. this.hide()
  66. }, duration)
  67. },
  68. // 隐藏Toast
  69. hide() {
  70. if (this.toastTimer) {
  71. clearTimeout(this.toastTimer)
  72. this.toastTimer = null
  73. }
  74. if (this.toastElement) {
  75. this.toastElement.classList.remove('show')
  76. setTimeout(() => {
  77. if (this.toastElement && this.toastElement.parentNode) {
  78. document.body.removeChild(this.toastElement)
  79. }
  80. this.toastElement = null
  81. }, 300)
  82. }
  83. }
  84. }
  85. // 全局Toast函数
  86. function showToastEffect(message, duration = 3000, type = 'info') {
  87. toastManager.show(message, duration, type)
  88. }
  89. // 导出到全局
  90. window.showToastEffect = showToastEffect
  91. window.toastManager = toastManager
  92. console.log('✅ H5 Toast工具已加载')