Accordion(Q/A)

Shin Woohyun·2021년 8월 10일
0

Q/A에서 자주 보는 펼쳤다가 접기

  1. html로 Q와 A를 형제 관계로 배치했다.
  2. css
    Q가 hover 상태, active class 추가된 상태일 때 색을 변경해준다.
    A는 overflow:hidden; 자식 크기에 맞춰주고, max-height:0 , transition: max-height 0.2s linear;max-height가 0이어서 보이지 않지만, 변경될 때는 효과를 준다.
  3. js
    모든 버튼을 가져와서 forEach로 같은 클릭 이벤트를 설정해준다.
const btns = document.querySelectorAll('.accordion');

btns.forEach(btn => 
    btn.addEventListener('click', function() {
        
        this.classList.toggle('active');

        const panel = this.nextElementSibling;

        panel.style.maxHeight = panel.style.maxHeight ? null : `${panel.scrollHeight}px`;
}))

🛶nextElementSibling

this.nextElementSibling : this의 다음 요소 형제를 선택한다.
this.nextSibiling : this 다음 text를 가져온다.
<-> Element.previousElementSibling

🚁Element.classList의 method

  • add( String [, String [, ...]] ) 클래스 값 추가. 이미 있으면 무시한다.
  • remove( String [, String [, ...]] ) 클래스 값 제거.
  • toggle( String [, force] )
    하나의 인수만 있을 때 : 클래스 값을 토글링. 있으면 제거하고 false 반환, 없으면 추가하고 true 반환
    두 번째 인수가 있을 때 : 두 번째 인수가 true이면 클래스 값을 추가하고, false이면 제거한다.
  • contains( String ) 클래스 값이 있는지 확인한다.
  • replace( oldClass, newClass )
  • item( Number ) 인덱스를 이용하여 클래스 값을 반환한다.

⛵️Element.scrollHeight

Element.scrollHeight 읽기 전용 속성은 요소 콘텐츠의 총 높이를 나타내며, 바깥으로 넘쳐서 보이지 않는 콘텐츠도 포함합니다.

다음 등식이 참인 경우 요소를 끝까지 스크롤한 것입니다.
element.scrollHeight - element.scrollTop === element.clientHeight
https://developer.mozilla.org/ko/docs/Web/API/Element/scrollHeight

type="checkbox" disabled, checked

🛸HTMLElement.style

The style read-only property returns the inline style of an element. A style declaration is reset by setting it to null or empty string.

//js에서 작성한 style은 html style 속성에 추가되기 때문
if(panel.style.maxHeight !== '0px') {
    panel.style.maxHeight = 0;
} else {
    panel.style.maxHeight = panel.scrollHeight + "px";
}

if(panel.style.maxHeight) {
    panel.style.maxHeight = null;
} else {
    panel.style.maxHeight = panel.scrollHeight + "px";
}

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

0개의 댓글