插件窝 干货文章 CSS动画如何实现元素高度的平滑过渡?

CSS动画如何实现元素高度的平滑过渡?

高度 过渡 Height transition 149    来源:    2025-03-23

在CSS中,可以通过使用transition属性来实现元素高度的平滑过渡。transition属性允许你定义元素在状态变化时的过渡效果,包括过渡的属性、持续时间、时间函数以及延迟时间。

以下是一个简单的示例,展示如何使用transition来实现元素高度的平滑过渡:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS Height Transition</title>
    <style>
        .box {
            width: 200px;
            height: 100px;
            background-color: lightblue;
            overflow: hidden; /* 防止内容溢出 */
            transition: height 0.5s ease; /* 定义高度过渡效果 */
        }

        .box.expanded {
            height: 300px;
        }

        .toggle-button {
            margin-top: 20px;
            padding: 10px 20px;
            font-size: 16px;
            cursor: pointer;
        }
    </style>
</head>
<body>

    <div class="box" id="box">
        <p>This is a box with a smooth height transition.</p>
    </div>

    <button class="toggle-button" onclick="toggleHeight()">Toggle Height</button>

    <script>
        function toggleHeight() {
            var box = document.getElementById('box');
            box.classList.toggle('expanded');
        }
    </script>

</body>
</html>

代码解释:

  1. HTML部分

    • 一个div元素(.box)用于展示内容。
    • 一个按钮用于触发高度的变化。
  2. CSS部分

    • .box类定义了初始的宽度、高度、背景颜色,并设置了overflow: hidden以防止内容在高度变化时溢出。
    • transition: height 0.5s ease; 定义了高度变化的过渡效果,持续时间为0.5秒,过渡效果为ease(缓入缓出)。
    • .box.expanded类定义了元素在展开状态下的高度。
  3. JavaScript部分

    • toggleHeight()函数通过切换.expanded类来改变元素的高度。

运行效果:

  • 初始状态下,.box的高度为100px。
  • 点击按钮后,.box的高度会平滑过渡到300px。
  • 再次点击按钮,.box的高度会平滑过渡回100px。

注意事项:

  • 如果你希望高度根据内容自动调整,可以使用max-height代替height,并设置一个足够大的值(例如max-height: 1000px;),这样可以避免在内容高度不确定时出现过渡不完整的问题。
  • 使用transition时,确保过渡的属性是可动画的(如heightwidthopacity等)。

通过这种方式,你可以轻松实现元素高度的平滑过渡效果。