JavaScriptでアコーディオンをコーディングしたので、メモしておく。今回は、ロード時にすべて閉じていて、dtタグをクリックするとプラスアイコンがマイナスアイコンに変化する仕様でコーディングした。
表示結果
See the Pen mdOzyLR by 山崎毅 (@nbudjgzu) on CodePen.
HTML(Pug)
body
dl.p-accordion
dt.p-accordion__trigger.js-accordion-trigger title
dd.p-accordion__body dammy text
dt.p-accordion__trigger.js-accordion-trigger title
dd.p-accordion__body dammy text
dt.p-accordion__trigger.js-accordion-trigger title
dd.p-accordion__body dammy text
CSS(SCSS)
.p-accordion {
max-width: 360px;
width: 100%;
&__trigger {
background-color: #e60012;
color: #fff ;
padding: .6em 1em;
position: relative;
cursor: pointer;
&::before,
&::after {
content: '';
display: block;
background-color: #fff;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
&::before {
width: 12px;
height: 2px;
right: 1em;
}
&::after {
width: 2px;
height: 12px;
right: 1.3em;
transition: opacity .36s;
}
&.is-active::after {
opacity: 0;
}
}
&__body {
background-color: #fff;
padding: 0 1em;
line-height: 0;
height: 0;
overflow: hidden;
opacity: 0;
transition: padding .36s, opacity .36s;
&.is-open {
padding: .6em 1em;
line-height: normal;
height: auto;
opacity: 1;
}
}
}
JavaScript
var trigger = document.querySelectorAll('.js-accordion-trigger');
for (var i = 0; i < trigger.length; i++) {
trigger[i].addEventListener('click', function() {
var body = this.nextElementSibling;
if (this.classList.contains('is-active')) {
this.classList.remove('is-active');
body.classList.remove('is-open');
} else {
this.classList.add('is-active');
body.classList.add('is-open');
}
});
}
(Visited 65 times, 1 visits today)