themePoc.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. /**
  2. * 通用JavaScript函数
  3. */
  4. // 当文档加载完成后执行
  5. $(document).ready(function() {
  6. // 初始化主题切换功能
  7. initThemeToggle();
  8. });
  9. /**
  10. * 初始化主题切换功能
  11. */
  12. function initThemeToggle() {
  13. // 使用事件委托绑定主题切换事件
  14. // 这样即使元素是动态添加的,事件也能正确触发
  15. $(document).on("click", "#theme-toggle, #theme-toggle-mobile", function(e) {
  16. e.preventDefault();
  17. const htmlElement = document.documentElement;
  18. const currentTheme = htmlElement.getAttribute("data-bs-theme");
  19. const newTheme = currentTheme === "dark" ? "light" : "dark";
  20. // 设置新主题
  21. htmlElement.setAttribute("data-bs-theme", newTheme);
  22. localStorage.setItem("theme", newTheme);
  23. // 更新主题文字
  24. updateThemeText(newTheme);
  25. });
  26. }
  27. /**
  28. * 更新主题文字
  29. */
  30. function updateThemeText(theme) {
  31. // 更新桌面端主题文字
  32. const themeText = document.getElementById("theme-text");
  33. if (themeText) {
  34. themeText.textContent = theme === "dark" ? "浅色主题" : "深色主题";
  35. }
  36. // 更新移动端主题文字
  37. const themeTextMobile = document.getElementById("theme-text-mobile");
  38. if (themeTextMobile) {
  39. themeTextMobile.textContent = theme === "dark" ? "浅色主题" : "深色主题";
  40. }
  41. }