我想根據簡單的 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>
uj5u.com熱心網友回復:
您的 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>
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/482088.html
標籤:javascript html css 颜色
上一篇:...args的泛型型別?
