在点击和加载时使用Vanilla JS设置CSS变量(使用localStorage)

时间:2018-08-27 22:13:47

标签: javascript local-storage css-variables

我试图通过单击按钮(主题应在单击时立即更改)和页面加载(应根据localStorage项设置主题)来更改:root上的一些css变量,从而使用JS设置一些简单的主题值)。

这里是我猜想我的“草稿” javascript似乎最有用,例外奇怪的是,按钮单击无济于事,但是在页面加载时,单击事件却会运行(每个事件依次执行) !)。我觉得我已经接近了,但显然我做错了。

const root = document.documentElement.style,
      button1 = document.getElementById("defaultBtn"),
      button2 = document.getElementById("darkBtn"),
      button3 = document.getElementById("lightBtn");
function setProperties(bg_color,fg_color,link_color,name) {
  root.setProperty("--bg",bg_color);
  root.setProperty("--fg",fg_color);
  root.setProperty("--link-color",link_color);
  console.log("Theme set to " + name);
}
function loadTheme() {
  let theme = localStorage.getItem("theme");
  switch (theme) {
    case "dark":
      setProperties("0%","59%","80%","dark");
      break;
    case "light":
      setProperties("100%","0%","100%","light");
      break;
    case "default":
      setProperties("90%","29%","90%","default");
      break;
    default:
      console.log("Theme has not been set.");
  }
}
function setTheme(name) {
  localStorage.setItem("theme", name);
  loadTheme();
}
window.addEventListener("DOMContentLoaded",loadTheme);
button1.addEventListener("click", setTheme("default"));
button2.addEventListener("click", setTheme("dark"));
button3.addEventListener("click", setTheme("light"));

1 个答案:

答案 0 :(得分:1)

这是您的问题。您正在调用该函数,而不是将其传递给事件侦听器,这意味着该函数将立即运行,而不是在单击按钮时运行。

button1.addEventListener("click", setTheme("default"));

解决方案是将代码包装在称为Closure的东西中。试试这个:

function setTheme(name) {
  return function() {
      localStorage.setItem("theme", name);
      loadTheme(name);
  }
}

这是一个例子:

function onClick(msg) {
	return function() {
  	console.log(msg)
  }
}

const button = document.getElementById('btn')
button.addEventListener('click', onClick('Hello'))
<button id="btn">Press Me</button>