我想根据简单的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代码中有三个问题需要解决:
-
元素上的
value
属性不引用您在段落元素上命名为value
的属性。要访问该属性的值,您需要使用Element.getAttribute()
。 事件侦听器回调函数中的 this
不指向事件的目标元素。要访问目标元素,您需要使用Event.target
。您想要侦听的事件很可能是
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>