아코디언 (Accordion)

아코디언
아코디언은 많은 양의 콘텐츠를 토글(toggle)을 통해 숨기거나 표시합니다:

아코디언 만들기

Step 1) HTML 코드 추가하기:
 

<button class=”accordion”>Section 1</button>
<div class=”panel”>
  <p>Lorem ipsum…</p>
</div>

<button class=”accordion”>Section 2</button>
<div class=”panel”>
  <p>Lorem ipsum…</p>
</div>

<button class=”accordion”>Section 3</button>
<div class=”panel”>
  <p>Lorem ipsum…</p>
</div>

Step 2) CSS 코드 추가하기:
아코디언을 css로 스타일링합니다:

/* Style the buttons that are used to open and close the accordion panel */
.accordion {
  background-color: #eee;
  color: #444;
  cursor: pointer;
  padding: 18px;
  width: 100%;
  text-align: left;
  border: none;
  outline: none;
  transition: 0.4s;
}

/* Add a background color to the button if it is clicked on (add the .active class with JS), and when you move the mouse over it (hover) */
.active, .accordion:hover {
  background-color: #ccc;
}

/* Style the accordion panel. Note: hidden by default */
.panel {
  padding: 0 18px;
  background-color: white;
  display: none;
  overflow: hidden;
}

Step 3) 자바스크립트 (JavaScript) 코드를 추가합니다:
 
아코디언에 토글 기능을 추가하기 위해 자바스크립트 코드를 활용합니다:

var acc = document.getElementsByClassName(“accordion”);
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener(“click”function() {
    /* Toggle between adding and removing the “active” class,
    to highlight the button that controls the panel */

    this.classList.toggle(“active”);

    /* Toggle between hiding and showing the active panel */
    var panel = this.nextElementSibling;
    if (panel.style.display === “block”) {
      panel.style.display = “none”;
    } else {
      panel.style.display = “block”;
    }
  });
}