You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript实现红色Div悬停缓增高度至顶部、移出缓降效果

实现悬停时动态改变Div高度的动画效果

看起来你已经有了初步的思路,我来帮你补全并优化代码,完美实现你想要的效果~

首先,你的代码用到了jQuery的animate()方法,所以需要先引入jQuery库。另外,要注意处理动画队列的问题,避免快速移入移出导致的动画延迟。下面是完整的可运行代码:

<!doctype html>
<html>
<head>
    <meta charset="utf-8">
    <title>animate</title>
    <!-- 引入jQuery库 -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        /* 设置页面黑色背景,清除默认边距 */
        body {
            background-color: #000;
            margin: 0;
            padding: 0;
            min-height: 100vh; /* 确保页面占满视口高度 */
        }
        /* 红色Div的初始样式 */
        #first {
            width: 200px;
            height: 100px;
            background-color: #ff0000;
            margin-top: 200px; /* 可调整初始位置,方便观察效果 */
        }
    </style>
</head>
<body>
    <div id="first"></div>

    <script>
        // 等待DOM加载完成后执行逻辑
        $(document).ready(function() {
            // 缓存初始高度和Div元素,提升性能
            const initialHeight = 100;
            const $targetDiv = $('#first');

            // 鼠标悬停时:高度缓慢增加至视口顶部(填满整个视口高度)
            $targetDiv.on('mouseenter', function() {
                // stop()清空动画队列,避免快速操作导致的动画滞后
                $targetDiv.stop().animate({
                    height: $(window).height() + 'px'
                }, 800); // 800毫秒完成动画,数值越大速度越慢,可自行调整
            });

            // 鼠标移出时:高度缓慢恢复初始值
            $targetDiv.on('mouseleave', function() {
                $targetDiv.stop().animate({
                    height: initialHeight + 'px'
                }, 800);
            });
        });
    </script>
</body>
</html>

关键细节说明:

  • 引入jQuery:animate()是jQuery提供的动画方法,必须先引入库才能正常运行。
  • 动画队列处理:加入stop()方法,当用户快速多次移入移出Div时,会停止当前动画并执行新动画,避免出现“卡顿滞后”的问题。
  • 高度计算:用$(window).height()获取当前浏览器视口高度,确保Div能准确延伸到页面顶部。
  • 速度控制:animate()的第二个参数是动画时长(单位毫秒),你可以根据需求调整数值,比如1000就是1秒完成动画。
  • 样式优化:给body设置min-height:100vh,确保黑色背景铺满整个视口,不会因为内容少出现空白。

如果你的需求是让Div的顶端直接延伸到页面顶部(而非高度填满视口),可以调整动画逻辑,同时修改top和height属性,示例如下:

// 先给#first添加CSS:position: relative
$targetDiv.on('mouseenter', function() {
    const currentTop = $targetDiv.offset().top;
    $targetDiv.stop().animate({
        top: 0,
        height: currentTop + initialHeight + 'px'
    }, 800);
});

$targetDiv.on('mouseleave', function() {
    $targetDiv.stop().animate({
        top: 200, // 回到初始top值,和CSS保持一致
        height: initialHeight + 'px'
    }, 800);
});

内容的提问来源于stack exchange,提问作者Atif Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 04:10:23