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

hover时宽度从0过渡到auto的按钮卡顿修复及优化需求

修复悬停卡顿的按钮过渡效果

我正在制作一个鼠标悬停后显示文本的按钮。目前当鼠标悬停约2秒后,按钮似乎会卡在悬停状态,需要修复该问题并让过渡效果更流畅。

按钮悬停卡顿效果

问题原因分析

  1. .button-text-container中重复设置了width: 0和width: fit-content,属性冲突导致初始状态异常
  2. max-width设置为过大的1275px,过渡时长1秒,鼠标移出后收缩动画延迟,容易触发重复悬停导致卡顿
  3. 仅针对max-width设置过渡,宽度变化逻辑不够流畅

修复后的代码

CSS

.button {
  width: fit-content;
  height: fit-content;
  padding: 10px 15px;
  background-color: #323232;
  color: white;
  border-radius: 10px;
  align-items: center;
  justify-content: center;
  display: flex;
  cursor: pointer;
  position: relative;
  border: 1px solid #bdc3c7;
  /* 确保按钮布局稳定,避免宽度突变导致鼠标触发问题 */
  white-space: nowrap;
}

.button-text-container {
  order: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  white-space: nowrap;
  overflow: hidden;
  /* 初始状态隐藏文本容器 */
  width: 0;
  max-width: 0;
  /* 避免被压缩 */
  flex-shrink: 0;
  /* 同时过渡width和max-width,让展开/收缩更流畅 */
  transition: all 0.3s ease-in-out;
  font-size: 1.5em;
}

.button-icon-container {
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 10px;
  font-size: 1.6em;
}

.button:hover .button-text-container {
  /* 设置合理的最大宽度,匹配文本实际宽度 */
  max-width: 200px;
  width: fit-content;
}

.button-text-container > span {
  margin: 10px;
}

HTML

<div class="button">
  <div class="button-icon-container">icon</div>
  <div class="button-text-container"><span>test</span></div>
</div>

修改说明

  • 移除.button-text-container中冲突的width设置,明确初始状态为width: 0和max-width: 0
  • 将过渡时长从1秒调整为0.3秒,同时过渡所有相关属性,提升流畅度
  • 将max-width的最大值改为合理的200px,避免过渡时的不必要延迟
  • 给.button添加white-space: nowrap,确保按钮布局稳定,减少鼠标触发区域的突变

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 12:25:43