Created
November 26, 2019 04:14
-
-
Save smagch/46140c3b2358288340deeaaee4247365 to your computer and use it in GitHub Desktop.
open/collapse for an element with `height: auto`
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<style> | |
.item { | |
display: block; | |
overflow: hidden; | |
} | |
.head { | |
height: 30px; | |
line-height: 30px; | |
background: tomato; | |
color: white; | |
} | |
.content { | |
opacity: 0; | |
visibility: hidden; | |
border: 1px solid #eee; | |
height: 0; | |
transition: all 0.3s; | |
overflow: hidden; | |
} | |
.content.active { | |
opacity: 0; | |
visibility: visible; | |
height: auto; | |
} | |
</style> | |
</head> | |
<body> | |
<div class="item"> | |
<div class="head">head</div> | |
<div class="content">body</div> | |
</div> | |
hoge | |
<script> | |
const item = document.querySelector('.item'); | |
const head = document.querySelector('.head'); | |
const content = document.querySelector('.content'); | |
head.addEventListener('click', () => { | |
content.classList.toggle('active'); | |
if (content.classList.contains('active')) { | |
const height = content.getBoundingClientRect().height; | |
content.style.height = '0px'; | |
window.requestAnimationFrame(() => { | |
content.style.height = `${height}px`; | |
content.style.opacity = 1; | |
}); | |
} else { | |
content.style.height = ''; | |
} | |
}); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment