在本地存储中保存两个相反的函数以应用选定的主题- jQuery

8yparm6h  于 2022-11-22  发布在  jQuery
关注(0)|答案(1)|浏览(113)

我有两个函数做相反的动作,每一个应用一个主题时,一个按钮被点击,如何保存主题或数据在这个函数在本地存储?以便当用户重新加载页面或改变页面的主题仍然是一个?
下面是我代码:

function orangeThemeActivation() {
    $("#orange-theme").removeAttr("disabled", "disabled");
    $(".to-green-blue-theme").attr(
      "style",
      "display: block !important; background: linear-gradient(to right, #14b0af 0%, #14b0af 50%, #004AAB 50%, #004AAB 100%); vertical-align:middle !important;"
    );
    $(this).attr("style", "display: none !important");
    $("body").addClass("orange-mode");
    $("body").removeClass("green-blue-mode");
    $("img[src*='/images/']").prop("src", (_index, oldURL) => {
      const url = new URL(oldURL);
      url.pathname = url.pathname.replace("/assets/images/", "/assets/orange/");
      return url;
    });
  }
  
  function greenBlueThemeActivation() {
    $("#orange-theme").attr("disabled", "disabled");
    $(".to-orange-theme").attr(
      "style",
      "display: block !important; background: orange !important; vertical-align:middle !important;"
    );
    $(this).attr("style", "display: none !important");
    $("body").addClass("green-blue-mode");
    $("body").removeClass("orange-mode");
    $("img[src*='/orange/']").prop("src", (_index, oldURL) => {
      const url = new URL(oldURL);
      url.pathname = url.pathname.replace("/assets/orange/", "/assets/images/");
      return url;
    });
  }
  
  $("#green-blue-color-changer").click(greenBlueThemeActivation);
  $("#orange-color-changer").click(orangeThemeActivation);
deyfvvtc

deyfvvtc1#

1.让每个函数在触发时使用setItem()更改localStorage

Add localStorage.setItem('lastThemeApplied', 'orangeTheme') in orangeThemeActivation() function.

Add localStorage.setItem('lastThemeApplied', 'greenBlueTheme') in greenBlueThemeActivation() function.

1.通过使用getItem()触发与localStorage中的值对应的函数来设置主题

window.onLoad = () => {
  if (localStorage.getItem('lastThemeApplied') === 'orangeTheme') {
    orangeThemeActivation();
  } else if (localStorage.getItem('lastThemeApplied') === 'greenBlueTheme') {
    greenBlueThemeActivation();
  }
}

相关问题