[英]How to toggle font awesome icon via class (pure CSS)
I'm working on a small project which is going to have a light/dark mode toggle but I'm struggling to toggle the class on the tag.我正在做一个小项目,该项目将有一个亮/暗模式切换,但我正在努力切换标签上的 class。
So I'm using font awesome for the icons here is my code:所以我为图标使用了很棒的字体,这是我的代码:
HTML: HTML:
<i class="fas fa-moon" id="toggle"></i>
JS: JS:
function classToggle() {
document.getElementById("toggle").classList.toggle('fas fa-moon');
document.getElementById("toggle").classList.toggle('fas fa-sun');
}
document.querySelector('#toggle').addEventListener('click', classToggle);
the above code gave me the error:上面的代码给了我错误:
InvalidCharacterError: The string contains invalid characters.
InvalidCharacterError:字符串包含无效字符。
for the JS I have also tried:对于 JS 我也尝试过:
function classToggle() {
this.classList.toggle('fas fa-moon');
this.classList.toggle('fas fa-sun');
}
document.querySelector('#toggle').addEventListener('click', classToggle);
but this doesn't work either and gave me the error:但这也不起作用,并给了我错误:
TypeError: undefined is not an object (evaluating 'this.classList.toggle')
TypeError: undefined is not an object(评估“this.classList.toggle”)
I got the code above from https://codepen.io/jacknifey/pen/XWJaKZr and it worked perfectly, but as soon as I changed the class names to the font awesome ones it stoped working.我从https://codepen.io/jacknifey/pen/XWJaKZr获得了上面的代码,它运行良好,但是一旦我将 class 名称更改为令人敬畏的字体,它就停止工作了。 Maybe it's something to do with the SVG's.
也许这与SVG有关。 If so can anyone suggest an alternative method.
如果是这样,任何人都可以提出替代方法。
Stay Safe Thanks, Jamie:)保持安全谢谢,杰米:)
You don't need to put fas
into classList.toggle
method.您不需要将
fas
放入classList.toggle
方法。
function classToggle() { document.getElementById("toggle").classList.toggle('fa-moon'); document.getElementById("toggle").classList.toggle('fa-sun'); } document.querySelector('#toggle').addEventListener('click', classToggle);
<link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css" rel="stylesheet" /> <i class="fas fa-moon" id="toggle"></i>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.