CSS 特效橫向風(fēng)琴(accordion)是一種通過 CSS 動(dòng)畫使得內(nèi)容展示具有交互性的效果,它類似于搖滾樂器風(fēng)琴,可以通過點(diǎn)擊或移動(dòng)鼠標(biāo)來切換展示內(nèi)容。
.accordion { display: flex; flex-direction: column; justify-content: center; align-items: center; width: 100%; max-width: 1200px; margin: 0 auto; padding: 10px; } .accordion__item { width: 100%; max-width: 800px; margin-bottom: 10px; overflow: hidden; } .accordion__item:eq(0) { margin-top: 10px; } .accordion__title { display: flex; justify-content: space-between; align-items: center; position: relative; background-color: #f2f2f2; border-radius: 5px; padding: 10px; cursor: pointer; } .accordion__title::before { content: ""; position: absolute; top: 50%; right: 10px; transform: translateY(-50%); width: 20px; height: 20px; background: url(arrow.png) no-repeat; background-size: contain; transition: transform 0.3s ease-in-out; } .accordion__title--active::before { transform: translateY(-50%) rotate(180deg); } .accordion__content { display: none; padding: 10px; } .accordion__content--active { display: block; }
以上是 CSS 代碼,來講講如何使用它實(shí)現(xiàn)橫向風(fēng)琴效果。
首先,我們需要在 HTML 中添加對應(yīng)的代碼:
<div class="accordion"> <div class="accordion__item"> <div class="accordion__title">標(biāo)題1</div> <div class="accordion__content">內(nèi)容1</div> </div> <div class="accordion__item"> <div class="accordion__title">標(biāo)題2</div> <div class="accordion__content">內(nèi)容2</div> </div> <div class="accordion__item"> <div class="accordion__title">標(biāo)題3</div> <div class="accordion__content">內(nèi)容3</div> </div> </div>
然后,我們只需要在 JS 中添加對應(yīng)操作來實(shí)現(xiàn)交互效果:
const titles = document.querySelectorAll(".accordion__title"); titles.forEach((title) =>{ title.addEventListener("click", function() { // 找到當(dāng)前點(diǎn)擊的 accodion item const item = this.parentNode; const content = this.nextElementSibling; const isActive = item.classList.contains("accordion__item--active"); // 判斷是否激活,如果是就取消激活狀態(tài) if (isActive) { item.classList.remove("accordion__item--active"); content.classList.remove("accordion__content--active"); } else { // 否則就添加激活狀態(tài) item.classList.add("accordion__item--active"); content.classList.add("accordion__content--active"); } }); });
通過添加上述代碼,我們就可以在頁面展示一個(gè)橫向風(fēng)琴效果,用戶可以通過點(diǎn)擊標(biāo)題切換展示內(nèi)容。