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

如何实现调用函数时SVG图片放大并移动至父div居中的动画

实现方法

你需要补全两部分代码:一是给父级导航容器加相对定位,保证logo定位参考系正确;二是在openNav函数中补充logo的缩放、位移动画逻辑,动画放在导航展开完成的回调里执行,避免位置计算偏差。

修改后的CSS代码

在原有.topnav样式中新增相对定位属性,其余原有样式保持不变:

@import url('https://fonts.googleapis.com/css2?family=Hind:wght@300;400&display=swap');
/* font-family: 'Hind', sans-serif; */

html, body {
  height: 100%;
  width: 100%;
  margin: 0px;
  background: rgb(229,239,243);
  background: linear-gradient(0deg, rgba(229,239,243,1) 0%, rgba(181,232,255,1) 100%);
}

.topnav {
  /* 新增相对定位,作为logo绝对定位的参考系 */
  position: relative;
  background-color: #2541B2;
  border-bottom: 2px solid black;
  overflow: hidden;
  color: white;
  padding: 5px 5px 2px 12px;
  font-family: 'Hind', sans-serif;
  font-weight: 400;
  font-size: 30px;
}

#logo{
  height: 40px;
  float: left;
  margin-right: 5px;
}

修改后的JS代码

在openNav函数中补充logo动画逻辑,其余原有逻辑保持不变:

function openNav(){
  $("#topnav").animate({height:'100%'}, function() {
    // 导航完全展开后计算动画参数,避免位置计算错误
    const targetLogoHeight = $(window).height() * 0.8; // 目标高度为屏幕高度80%
    const navWidth = $(this).width();
    const navHeight = $(this).height();

    $("#logo")
      .css({
        float: "none",
        position: "absolute",
        marginRight: 0
      })
      .animate({
        height: targetLogoHeight,
        // 因为使用的SVG是正方形等比资源,宽高一致,直接计算居中偏移即可
        left: (navWidth - targetLogoHeight) / 2 + "px",
        top: (navHeight - targetLogoHeight) / 2 + "px"
      }, 300);
  })
  $("#title").fadeOut()
}

openNav();

说明

  • 动画放在#topnav的animate回调中执行,是为了等导航栏完全展开为全屏高度后再获取容器尺寸,计算出来的居中位置才准确
  • 动画执行前先清除logo原有浮动、边距属性,切换为绝对定位,避免原有布局属性影响位移效果
  • 所用SVG为矢量格式,缩放不会出现失真问题,如果后续替换为非等比图片,需要先获取图片原始宽高比计算对应目标宽度,避免图片拉伸

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 15:12:45