Ir para o conteúdo

Construir UINão tentada

Accordion de abertura múltipla

HTML / CSS / JSDificuldade: fácil

Um accordion de títulos de livros em que várias seções podem ficar abertas ao mesmo tempo, cada uma alternando seu próprio painel.

Prévia: seu documento HTML como está. localStorage e IndexedDB são redefinidos quando a prévia recarrega.

Requisitos · 0 / 5

Marque cada requisito depois de conferi-lo na prévia.
Ver solução de referência
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Book accordion</title>
<style>
body {
font-family: system-ui, sans-serif;
margin: 24px;
max-width: 640px;
color: #1f2937;
}
.section {
border: 1px solid #d1d5db;
border-radius: 8px;
margin-bottom: 8px;
overflow: hidden;
}
.section h2 {
margin: 0;
font-size: 1rem;
}
.header {
display: flex;
justify-content: space-between;
align-items: center;
width: 100%;
padding: 12px 16px;
border: none;
background: #f3f4f6;
font: inherit;
font-weight: 600;
text-align: left;
cursor: pointer;
}
.header:focus-visible {
outline: 3px solid #2563eb;
outline-offset: -3px;
}
.icon {
display: inline-block;
width: 1em;
text-align: center;
}
.panel {
padding: 12px 16px;
}
.panel p {
margin: 0;
}
.options {
margin-bottom: 16px;
}
</style>
</head>
<body>
<h1>Book titles</h1>
<div class="options">
<label><input type="checkbox" id="single" /> Only one section open at a time</label>
</div>
<div id="accordion"></div>
<script>
const books = [
{
title: 'Pride and Prejudice',
author: 'Jane Austen',
summary: 'Elizabeth Bennet and Mr Darcy misjudge each other before slowly seeing past first impressions.',
},
{
title: 'Moby-Dick',
author: 'Herman Melville',
summary: 'A whaling captain chases the white whale that took his leg, dragging his crew along with him.',
},
{
title: 'Frankenstein',
author: 'Mary Shelley',
summary: 'A young scientist builds a living being and then abandons it, with tragic results for both.',
},
{
title: 'The Time Machine',
author: 'H. G. Wells',
summary: 'An inventor travels far into the future and finds humanity split into two very different species.',
},
];
const accordion = document.getElementById('accordion');
const singleToggle = document.getElementById('single');
books.forEach((book, i) => {
const section = document.createElement('div');
section.className = 'section';
const heading = document.createElement('h2');
const header = document.createElement('button');
header.type = 'button';
header.className = 'header';
header.id = `header-${i}`;
header.setAttribute('aria-expanded', 'false');
header.setAttribute('aria-controls', `panel-${i}`);
const label = document.createElement('span');
label.textContent = book.title;
const icon = document.createElement('span');
icon.className = 'icon';
icon.setAttribute('aria-hidden', 'true');
icon.textContent = '+';
header.append(label, icon);
heading.appendChild(header);
const panel = document.createElement('div');
panel.className = 'panel';
panel.id = `panel-${i}`;
panel.setAttribute('role', 'region');
panel.setAttribute('aria-labelledby', header.id);
panel.hidden = true;
const text = document.createElement('p');
text.textContent = `${book.author}. ${book.summary}`;
panel.appendChild(text);
section.append(heading, panel);
accordion.appendChild(section);
});
function setOpen(header, open) {
header.setAttribute('aria-expanded', String(open));
header.querySelector('.icon').textContent = open ? '−' : '+';
document.getElementById(header.getAttribute('aria-controls')).hidden = !open;
}
// One listener for every header.
accordion.addEventListener('click', (e) => {
const header = e.target.closest('.header');
if (!header) return;
const willOpen = header.getAttribute('aria-expanded') !== 'true';
if (singleToggle.checked && willOpen) {
accordion.querySelectorAll('.header[aria-expanded="true"]').forEach((h) => setOpen(h, false));
}
setOpen(header, willOpen);
});
// Switching to single-open mode keeps only the first open section.
singleToggle.addEventListener('change', () => {
if (!singleToggle.checked) return;
const open = [...accordion.querySelectorAll('.header[aria-expanded="true"]')];
open.slice(1).forEach((h) => setOpen(h, false));
});
</script>
</body>
</html>
Carregando editor…