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

如何为滚动缩小的logo添加与header一致的transition过渡效果

问题排查与解决方案

  • 第一个核心问题:logo初始宽度为auto,CSS transition 不支持对auto属性值的变化做过渡动画,必须明确指定logo的初始宽度
  • 第二个常见问题:slow-transition类的优先级不够,可能被主题自带的logo样式、id选择器的样式覆盖,导致transition规则不生效
  • 第三个优化点:当前两个滚动监听事件的触发阈值不一致(logo是5px、header是30px),会导致两个动画不同步,可合并监听逻辑统一阈值

修正代码

CSS 部分

/* 明确指定logo的初始宽度和过渡规则,id选择器优先级更高避免被覆盖 */
#Logo {
  width: 150px;
  transition: width 0.9s ease-out !important;
}

.reduce-section-padding {
  transition: all 0.9s ease-out 0s;
  padding-top: 0px !important;
  padding-bottom: 0px !important;
  margin-top: 0px !important;
}
 
.increase-row-width {
  transition: all 0.9s ease-out 0s;
  width: 100% !important;
}
 
.slow-transition {
  transition: all 0.9s ease-out 0s;
}
 
#main-content {
  margin-top: 0vw;
}

JavaScript 部分

合并滚动监听逻辑,减少性能消耗同时同步动画触发时机:

add_action( 'wp_head', function () { ?>
    <script>
    jQuery(function($){
      $(window).scroll(function() {
          const scrollTop = $(document).scrollTop();
          const Logo = document.getElementById("Logo");
          if (scrollTop > 30) {
            Logo.style.width = '80px';
            $('#section-padding').addClass('reduce-section-padding');
            $('#row-width').addClass('increase-row-width');
        } else {
            Logo.style.width = '150px';
            $('#section-padding').removeClass('reduce-section-padding');
            $('#row-width').removeClass('increase-row-width');
        }
      });
    });
    </script>
    <?php } );

验证方法

修改后打开浏览器开发者工具(F12),选中logo元素,查看「计算样式」中的transition属性,确认规则已生效没有被划掉,滚动页面即可看到过渡效果。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 10:54:02