我有一些普通的 JavaScript 可以監聽點擊,當點擊時,會發生四件事:
當點擊另一個按鈕時,第一次點擊的按鈕會發生相反的情況,新增的類別被刪除,“aria-expanded”屬性被重新設定為“false”,div 再次隱藏(再次設定為CSS)並且“之後”文字恢復為“閱讀更多”。
但是,如果第二次點擊同一個按鈕,同時新增的類別按預期刪除,並且 div 再次隱藏,「aria-expanded」屬性不會重新設定為「false」。誰能解釋一下原因並告訴我該做什麼? (沒有 jQuery,謝謝)。
const tips = Array.from(document.querySelectorAll('.toggle-button')); tips.forEach((tip) => { tip.addEventListener('click', () => { tips .filter((f) => f !== tip) .forEach((f) => { f.setAttribute('aria-expanded', false); f.classList.remove('form-opened'); }); tip.setAttribute('aria-expanded', true); tip.classList.contains('form-opened'); tip.classList.toggle('form-opened'); }); });
.toggle-button ~ .tips { display: none; } button.toggle-button[aria-expanded="false"]:after { content: "Read more"; } .toggle-button.form-opened ~ .tips { display: block; margin-bottom: 16px; } button.toggle-button[aria-expanded="true"]:after { content: "Close info"; cursor: pointer; } .visually-hidden { border: 0; padding: 0; margin: 0; position: absolute; height: 1px; width: 1px; overflow: hidden; white-space: nowrap; display: inline-block; }
<div class="toggle-box"> <label for="button-1" class="visually-hidden toggle-list">Open or Close info</label><button id="button-1" class="toggle-button" aria-expanded="false"></button> <div class="tips"> Here is some text that is to be revealed </div> </div> <div class="toggle-box"> <label for="button-2" class="visually-hidden toggle-list">Open or Close info</label><button id="button-2" class="toggle-button" aria-expanded="false"></button> <div class="tips"> Here is some text that is to be revealed </div> </div> <div class="toggle-box"> <label for="button-3" class="visually-hidden toggle-list">Open or Close info</label><button id="button-3" class="toggle-button" aria-expanded="false"></button> <div class="tips"> Here is some text that is to be revealed </div> </div>
我看過一些類似的查詢,但不完全相同或非常舊,或者它們使用 jQuery。
點擊一個按鈕只會將所有其他按鈕的
aria-expanded
屬性設為 false。您還必須切換目前按鈕的狀態: