因此,我正在创建此按钮,该按钮在单击时会扩展,在再次单击时会隐藏数据。我已经使它工作了,但是在刷新之前它只工作了一次,然后我想我需要采取一种不同的方法,即切换按钮本身的类,而不是切换数据出现的div。我的问题是,为此,我只需要切换按钮具有javascript的两个类之一即可。我怎么做?
const expandMovies = document.querySelector("#btnMovies");
expandMovies.addEventListener("click", toggleMovies)
function toggleMovies() {
if (expandMovies.classList.contains("inactive")) {
getMovies();
expandMovies.classList.toggle("active");
} else {
parentMovies.style.display="none";
expandMovies.classList.toggle("inactive");
}
};
答案 0 :(得分:0)
您可以使用toggle方法的第二个属性,该属性强制强行删除或添加类。以下是可帮助您的代码段。
const expandMovies = document.querySelector("#btnMovies");
expandMovies.addEventListener("click", toggleMovies)
function toggleMovies() {
if (expandMovies.classList.contains("inactive")) {
getMovies();
expandMovies.classList.toggle("inactive",false);
expandMovies.classList.toggle("active",true);
} else {
parentMovies.style.display="none";
expandMovies.classList.toggle("active",false);
expandMovies.classList.toggle("inactive",true);
}
};