hint-view.js 3.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // 提示消息组件
  2. (function() {
  3. let hintView = null;
  4. let hintMessage = null;
  5. let hideTimeout = null;
  6. function init() {
  7. // 如果 hint-view.html 已经加载,直接获取元素
  8. hintView = document.getElementById('hintView');
  9. hintMessage = document.getElementById('hintMessage');
  10. // 如果元素不存在,创建它们
  11. if (!hintView) {
  12. hintView = document.createElement('div');
  13. hintView.className = 'hint-view';
  14. hintView.id = 'hintView';
  15. hintMessage = document.createElement('span');
  16. hintMessage.className = 'hint-message';
  17. hintMessage.id = 'hintMessage';
  18. const hintContent = document.createElement('div');
  19. hintContent.className = 'hint-content';
  20. const icon = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
  21. icon.setAttribute('class', 'hint-icon');
  22. icon.setAttribute('width', '20');
  23. icon.setAttribute('height', '20');
  24. icon.setAttribute('viewBox', '0 0 20 20');
  25. icon.setAttribute('fill', 'currentColor');
  26. const path = document.createElementNS('http://www.w3.org/2000/svg', 'path');
  27. path.setAttribute('d', 'M10 0C4.48 0 0 4.48 0 10s4.48 10 10 10 10-4.48 10-10S15.52 0 10 0zm-1 15l-5-5 1.41-1.41L9 12.17l7.59-7.59L18 6l-9 9z');
  28. icon.appendChild(path);
  29. hintContent.appendChild(icon);
  30. hintContent.appendChild(hintMessage);
  31. hintView.appendChild(hintContent);
  32. document.body.appendChild(hintView);
  33. }
  34. }
  35. function show(message, type = 'success', duration = 3000) {
  36. init();
  37. // 清除之前的定时器
  38. if (hideTimeout) {
  39. clearTimeout(hideTimeout);
  40. hideTimeout = null;
  41. }
  42. // 移除之前的类型类
  43. hintView.classList.remove('success', 'error', 'warning', 'info', 'show', 'hide');
  44. // 设置消息和类型
  45. hintMessage.textContent = message;
  46. hintView.classList.add(type);
  47. // 显示提示
  48. requestAnimationFrame(() => {
  49. hintView.classList.add('show');
  50. });
  51. // 自动隐藏
  52. hideTimeout = setTimeout(() => {
  53. hide();
  54. }, duration);
  55. }
  56. function hide() {
  57. if (!hintView) return;
  58. // 添加隐藏动画类
  59. hintView.classList.remove('show');
  60. hintView.classList.add('hide');
  61. // 动画结束后移除类
  62. setTimeout(() => {
  63. hintView.classList.remove('hide', 'success', 'error', 'warning', 'info');
  64. hintMessage.textContent = '';
  65. }, 300); // 与 CSS 动画时间一致
  66. }
  67. // 导出全局函数
  68. window.HintView = {
  69. show: show,
  70. hide: hide,
  71. success: (message, duration) => show(message, 'success', duration),
  72. error: (message, duration) => show(message, 'error', duration),
  73. warning: (message, duration) => show(message, 'warning', duration),
  74. info: (message, duration) => show(message, 'info', duration)
  75. };
  76. })();