He estado tratando de implementar un prototipo que permita al usuario expandir o contraer elementos en una lista. Por ejemplo. El + indica un menú desplegable. Cuando inicie, le mostrará solo un elemento:
Farm + Click on the + and it shows you: Farm Field A+ Click on the + and it shows you: Farm Field A Bed A+ Bed B+ Click on the Bed A+ and it shows you: Farm Field A Bed A Row 1 Row 2 Bed B+ Click on the Bed B+ and it shows you: Field A + Bed A + Row 1 Row 2 Bed B + Row 3 Row 4Funciona si solo tiene un elemento que necesita expandirse. Cuando intenta hacer una lista anidada con varios elementos para expansiones, se desmorona (por ejemplo, cuando hace clic en el Campo A +, solo mostrará la Cama A + y no la Cama B +. Es HTML, basado en Javascript y un componente CSS. Yo prefiero usar Javascript, el código está en https://jsfiddle.net/jackmstein/ekfbcn71/7/
Se necesitará algo de CSS y JS para ayudar con la interactividad.
Pruebe algo como lo siguiente (¡código no probado por delante!)
<!-- Build a tree using nested lists. --> <ul> <li> <label>Farm</label> <span class="expander">+</span> <ul> ...various list items... </ul> </li> </ul> /* Hide the child tree items by default */ li > ul { display: hidden; } /* Show the immediate child tree if the parent has the [expanded] attribute */ li[expanded] > ul { display: block; } // For every span.expander found, when clicked, toggle the [expanded] attribute // on the parent <li> document.querySelectorAll('span.expander').addEventListener('click', e => { const element = e.target; const parent = element.closest('li'); parent.toggleAttribute('expanded'); });