如何通过CSS根变量设置一个简单的配色方案?



我想根据简单的CSS根变量设置配色方案。JavaScript不起作用:当单击其中一个选项时,它看不到/设置根变量。为了让这个简单的配色方案发挥作用,我忽略了什么?

const setTheme = theme => document.documentElement.className = theme;
document.getElementById('themeoptions').addEventListener('change', function() {
setTheme(this.value);
});
#themeoptions p{ /* User Interface */
display: inline-block;
text-decoration: underline;
}#themeoptions p:hover{cursor: pointer}

:root.light {
--bgr: #ddc;
--txt: #456;
}
:root.dark {
--bgr: #222;
--txt: #844;
}
:root.blue {
--bgr: #046;
--txt: #dde;
}

body {
background-color: var(--bgr);
color: var(--txt);
}
<div id="themeoptions">
<p value="light">Light</p>
<p value="dark">Dark</p>
<p value="blue">Blue</p>
</div>
<h1>Click on a theme to change the color scheme!</h1>

在JavaScript代码中有三个问题需要解决:

  1. 元素上的value属性不引用您在段落元素上命名为value的属性。要访问该属性的值,您需要使用Element.getAttribute()

  2. 事件侦听器回调函数中的
  3. this不指向事件的目标元素。要访问目标元素,您需要使用Event.target

  4. 您想要侦听的事件很可能是click事件(而不是change事件)。

const setTheme = theme => document.documentElement.className = theme;
document.getElementById('themeoptions').addEventListener('click', ({target}) => {
setTheme(target.getAttribute('value'));
});
#themeoptions p{ /* User Interface */
display: inline-block;
text-decoration: underline;
}#themeoptions p:hover{cursor: pointer}

:root.light {
--bgr: #ddc;
--txt: #456;
}
:root.dark {
--bgr: #222;
--txt: #844;
}
:root.blue {
--bgr: #046;
--txt: #dde;
}

body {
background-color: var(--bgr);
color: var(--txt);
}
<div id="themeoptions">
<p value="light">Light</p>
<p value="dark">Dark</p>
<p value="blue">Blue</p>
</div>
<h1>Click on a theme to change the color scheme!</h1>

最新更新