我有一些普通的 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。
P粉5093831502024-03-29 12:44:38
单击一个按钮只会将所有其他按钮的 aria-expanded
属性设置为 false。您还必须切换当前按钮的状态:
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'); }); // Toggle both aria-expanded attribute and form-opened class tip.setAttribute( "aria-expanded", tip.getAttribute("aria-expanded") == 'true' ? 'false' : 'true' ); tip.classList.toggle('form-opened'); }); });