CSS 및 JavaScript로 트리 보기를 생성하려면 코드는 다음과 같습니다 -
예시
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1" /> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } ul, #treeUL { list-style-type: none; } #treeUL { margin: 0; padding: 0; } .rootTree { cursor: pointer; user-select: none; font-size: 18px; font-weight: bold; color: blue; } li { font-size: 16px; color: crimson; font-weight: 500; } .rootTree::before { content: "\25B6"; color: black; display: inline-block; margin-right: 6px; } .rootTree-down::before { transform: rotate(90deg); } .children { display: none; } .active { display: block; } </style> </head> <body> <h1>Tree view example</h1> <ul id="treeUL"> <li> <span class="rootTree">Root</span> <ul class="children"> <li>/bin</li> <li>/etc</li> <li> <span class="rootTree">/home</span> <ul class="children"> <li>/home/Downloads</li> <li>/home/Pictures/</li> <li> <span class="rootTree">/home/Desktop</span> <ul class="children"> <li>/home/Desktop/file.txt</li> <li>/home/Desktop/file1.mp3</li> <li>/home/Desktop/file1.mp4</li> </ul> </li> </ul> </li> </ul> </li> </ul> <script> debugger; console.log('wow'); var toggler = document.querySelectorAll(".rootTree"); Array.from(toggler).forEach(item => { item.addEventListener("click", () => { item.parentElement .querySelector(".children") .classList.toggle("active"); item.classList.toggle("rootTree-down"); }); }); </script> </body> </html>
출력
위의 코드는 다음과 같은 출력을 생성합니다 -
캐럿을 클릭하여 트리 확장 시 -