我正在尝试学习JavaScript,并在单击图标时尝试在空圆圈图标和带有复选标记的圆圈之间切换。但是,它似乎不起作用。
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://kit.fontawesome.com/0c7c27ff53.js" crossorigin="anonymous"></script>
<head>
</head>
<body>
<i class="far fa-circle" id="toggle"></i>
<script>
document.addEventListener('click', (event) =>{
if(event.target.id == 'toggle'){
document.getElementById('toggle').classList.toggle("fas fa-check-circle");
}
});
</script>
</body>
</html>
答案 0 :(得分:1)
有时,定义元素默认 CSS比使用 is-*
类修饰符更有用-比使用 fas做时髦的东西类。看看:
const EL_tog = document.querySelector('#toggle');
EL_tog.addEventListener('click', () => {
EL_tog.classList.toggle("is-active");
});
#toggle:before {
font-family: "Font Awesome 5 Free";
content: "\f111";
font-style: normal;
}
#toggle.is-active:before {
font-family: "Font Awesome 5 Free";
content: "\f058";
}
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.14.0/css/all.min.css">
<i id="toggle"></i>
明天,即使您决定使用其他图标集,也无需更改HTML,只需更改CSS。毕竟是这一切-全部。
如果您想知道我从哪里得到CSS content:
的十六进制值,例如\f111
-不是big deal
答案 1 :(得分:1)
一个想法是使用堆叠图标,您只能处理一个类:
var icon = document.getElementById('toggle');
icon.addEventListener('click', (event) => {
icon.querySelector(':last-child').classList.toggle("fa-check-circle");
});
<script src="https://kit.fontawesome.com/0c7c27ff53.js" crossorigin="anonymous"></script>
<span class="fa-stack fa-2x" id="toggle">
<i class="far fa-circle fa-stack-2x"></i>
<i class="fas fa-stack-2x"></i> <!-- OR "far" for the other version -->
</span>
相关:https://fontawesome.com/how-to-use/on-the-web/styling/stacking-icons