我正在尝试使用Unicode在图标之间切换。我不确定自己在做什么错,我尝试使用其className进行切换,这对我也不起作用,任何答案都值得赞赏。 (我只想使用纯JavaScript而不使用jquery)
const burger = document.getElementById('toggle');
burger.addEventListener('click', (e) => {
const tog = e.target;
if (tog.innerHTML === "") {
nav.style.display = "flex";
tog.innerHTML = "";
} else {
nav.style.display = "none";
}
});
<header class="navbar">
<i class="fa" id="toggle"></i>
<nav class="menu">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Gallery</a>
<a href="#">Contact</a>
<a href="#">Search</a>
</nav>
</header>
答案 0 :(得分:1)
let burger = document.getElementById('mybtn');
function toggleBetweenClasses(el, c1, c2) {
el.classList.toggle(c1);
el.classList.toggle(c2);
}
function myToggleBetweenClasses(el, c1, c2) {
toggleBetweenClasses(burger, "fa-bars", "fa-times");
}
burger.addEventListener('click', myToggleBetweenClasses);
<link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css" integrity="sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU" crossorigin="anonymous">
<i class="fas fa-bars" id="mybtn"></i>
答案 1 :(得分:1)
@AlexandreJ提供了一个解决方案。
但是,如果您想使用特定的CSS类运行一个函数并使用另一个CSS类运行另一个函数,该怎么办?
您可以执行以下操作:
// fa-bars <-> fa-close
function toggleBetweenTwoClasses(el, c1, c2) {
var currentClass = el.getAttribute("class");
var newClass;
if (currentClass.indexOf(c1) !== -1) {
newClass = currentClass.replace(c1, c2);
// Do stuff 1
}
if (currentClass.indexOf(c2) !== -1) {
newClass = currentClass.replace(c2, c1);
// Do stuff 2
}
el.setAttribute("class", newClass);
}
function myToggleBetweenTwoClasses(el, c1, c2) {
toggleBetweenTwoClasses(document.getElementById("toggle"), "fa-bars", "fa-close");
}
var icon = document.getElementById("toggle");
icon.addEventListener("click", myToggleBetweenTwoClasses);
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">
<header class="navbar">
<i class="fa fa-bars" id="toggle"></i>
<nav class="menu">
<a href="#">Home</a>
<a href="#">About</a>
<a href="#">Gallery</a>
<a href="#">Contact</a>
<a href="#">Search</a>
</nav>
</header>