主要是利用了浏览器的渲染机制。
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.content {
background: blue;
width: 200px;
overflow: hidden;
height: 0;
}
</style>
</head>
<body>
<span class="btn">
测试
</span>
<div class="content">
<p>111111111111</p>
<p>222222222222</p>
<p>222222222222</p>
<p>222222222222</p>
<p>222222222222</p>
<p>222222222222</p>
<p>222222222222</p>
<p>222222222222</p>
<p>222222222222</p>
</div>
<script>
const btn = document.querySelector('.btn');
const content = document.querySelector('.content')
btn.onmouseenter = function () {
content.style.height = 'auto';
const {height} = content.getBoundingClientRect();
console.log(height);
//有回流,但是没有绘制,所以不会闪一下,界面看不出变化,但是拿到了高度
content.style.height = 0;
//不加content.offsetHeight,默认是直接渲染height + 'px',不会出现从0->height的动画
content.style.transition = 'height 0.5s';
//读取几何属性会造成强制回流,从而触发渲染
content.offsetHeight;
content.style.height = height + 'px';
}
btn.onmouseleave = function () {
content.style.height = 0;
}
</script>
</body>
</html>