トグルUIとは、クリックなどの操作で、ある要素を表示・非表示に切り替えるユーザーインターフェースのことです。ひとつの情報ブロックを必要なときだけ見せたいときに便利です。
このトグルUIでは、ボタンクリック時に `.is-open` クラスを付け外しすることで、JavaScriptで高さを計測して `height` を動的に変更し、CSSの `transition` を利用してスムーズなスライド開閉を実現しています。
<button class="toggle-button">もっと見る</button>
<div class="toggle-content">
これはトグルで表示・非表示を切り替えるコンテンツです。
</div>
.toggle-content {
height: 0;
overflow: hidden;
opacity: 0;
background-color: #f9fafb;
border-radius: 0.5rem;
padding: 0 1rem;
margin-top: 1rem;
box-sizing: content-box;
transition: height 0.4s ease, opacity 0.4s ease, padding 0.4s ease;
}
.toggle-content.is-open {
opacity: 1;
padding: 1rem;
}
.toggle-button {
background-color: #3b82f6;
color: white;
padding: 0.75rem 1.25rem;
border: none;
border-radius: 0.375rem;
cursor: pointer;
font-weight: 600;
transition: background-color 0.3s;
}
.toggle-button:hover {
background-color: #2563eb;
}
document.addEventListener('DOMContentLoaded', function() {
const button = document.querySelector('.toggle-button');
const content = document.querySelector('.toggle-content');
button.addEventListener('click', () => {
if (content.classList.contains('is-open')) {
content.style.height = '0px';
content.classList.remove('is-open');
} else {
const height = content.scrollHeight + 'px';
content.style.height = height;
content.classList.add('is-open');
}
});
});