Skip to content

高度自适应过渡效果

在平时封装UI组件的时候,有这么一个问题,那就是自适应的宽度或者高度,怎么做才能有过渡效果?

既然要做自适应宽高的组件,那么宽度和高度肯定不能写死,只能用auto或者max-widthmax-height等去设置。如果用了max这种方式,那么怎样才能决定这个最大值是多少呢?如果最大值写多了的话,那么过渡时长会根据内容的多与少存在差异。如果使用了auto的方式,CSS的过渡效果又只针对数字型的值生效,从0到auto显然是没办法产生过渡效果的。

如果css做不到,那么就上js,完整的实现代码如下:

html
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>高度自适应过渡动画</title>
  <link rel="stylesheet" href="./css/index.css">
</head>

<body>
  <div class="btn">
    hover me
    <div class="detail">
      <div class="content">
        <div class="inner">
          In the ever-evolving world of technology, the internet has become an indispensable tool for people of all
          ages. It has
          revolutionized the way we communicate, work, and learn. The internet has made it easier for people to connect
          with
          others from all corners of the globe, fostering a sense of global community.
        </div>
      </div>
    </div>
  </div>
  <script src="./js/index.js"></script>
</body>

</html>
css
.btn {
  position: relative;
  border: none;
  outline: none;
  background-color: #409eff;
  color: #fff;
  display: inline-block;
  line-height: 1;
  cursor: pointer;
  text-align: center;
  transition: 0.1s;
  font-weight: 500;
  user-select: none;
  padding: 12px 20px;
  font-size: 14px;
  border-radius: 4px;
}

.btn:hover {
  background-color: #66b1ff;
}

.btn:active {
  background-color: #3a8ee6;
}

.btn:disabled {
  background: #66b1ff80;
  cursor: not-allowed;
}

.detail {
  position: absolute;
  left: 0;
  top: 100%;
  /** 重点 */
  height: 0;
  overflow: hidden;
  padding-top: 0.2em;
  transition: 0.5s;
}

.content {
  width: 200px;
  border-radius: 5px;
  background: #007bff;
  color: #fff;
  line-height: 1.5;
}

.inner {
  padding: 20px;
}
js
const btn = document.querySelector('.btn')
const detail = document.querySelector('.detail')
// 鼠标进入
btn.onmouseenter = () => {
  detail.style.height = 'auto'
  const { height } = detail.getBoundingClientRect()
  detail.style.height = 0
  detail.getBoundingClientRect()
  detail.style.height = `${height}px`
}
// 鼠标离开
btn.onmouseleave = () => {
  detail.style.height = '0px'
}

效果预览:



参考视频:抖音 - 渡一Web前端学习频道 - 如何实现高度自动的过渡