1 回答

TA貢獻1874條經驗 獲得超12個贊
這是如何在 vanilla JS 中切換類的簡單示例。然后,您只需通過 CSS 進行樣式設置即可。
// Cache the DOM element for continued use
var btn = document.getElementById("btn");
// Attach event listener to button for 'click' event
btn.addEventListener("click", () =>
{
// Where we see if it has the class or not
// Is it inactive?
if (!btn.classList.contains("active"))
{
console.log("Added");
btn.classList.add("active");
} else // If it *is* currently active
{
console.log("Removed");
btn.classList.remove("active");
}
});
.btn {
padding: 1rem;
width: 200px;
transition: all 300ms ease-in-out;
}
.btn.active {
padding: 2rem;
width: 400px;
}
<button class="btn" id="btn">Click Me</button>
本質上,您使用 CSS 類作為不同樣式的目標,并僅使用 JS 來打開/關閉該類。這樣,您只需將 CSS 中的“toggle”類編輯為您想要的任何內容,并且代碼將始終有效。這通常是我們用于粘性導航欄等的方法。您只需添加/刪除另一個類,它就會覆蓋默認樣式。
- 1 回答
- 0 關注
- 152 瀏覽
添加回答
舉報