我一直在尝试在不使用 jquery 或其他库的情况下切换字体真棒图标,我想根据主题切换图标并有一些这样的图标。
<a class="sidebar-link" onclick="themify()">
<i id="theme-icon" class="fad fa-sun" style="--fa-secondary-opacity: 1;" aria hidden="true"></i>
<span class="sidebar-link-text themer" id="theme-text">theme</span>
</a>
并且作为函数
var state = "Day";
var prefers = "Day";
window.onload = function() {
if (window.matchMedia('(prefers-color-scheme)').media !== 'not all') {
if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
prefers = "Night";
document.getElementById("theme-icon").className = "fad fa-moon-stars";
}
state = prefers;
document.getElementById('theme-text').innerHTML = state;
}
function themify() {
var body = document.getElementsByTagName("BODY")[0];
switch (state) {
case "Day":
state = "Night";
document.getElementById('theme-text').innerHTML = state;
document.getElementById('theme-icon').className = "fad fa-moon-stars";
body.style.color = "white";
body.style.backgroundColor = "#1c1c1c";
break;
case "Night":
state = "Day";
document.getElementById('theme-text').innerHTML = state;
document.getElementById('theme-icon').className = "fad fa-sun";
body.style.color = "black";
body.style.backgroundColor = "white";
break;
}
}
该状态仅定义为两个状态;“Day”和“Night”,这个变量和 body 对象的颜色切换有效,但在页面加载后我不再能够更改图标。我需要直接修改 SVG 吗?
找到解决方案(感谢 John),如果您遇到同样的问题,请使用 element.classlist.remove(); 对于每个类项,然后通过 element.classlist.add() 添加新类;