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

点击菜单按钮实现CSS width平滑过渡失效问题求助

解决菜单宽度平滑过渡问题

问题原因

CSS过渡动画需要元素属性有明确的起始值和结束值。你的.menu元素默认宽度为auto(由内容决定),浏览器无法基于这个值计算过渡的中间状态,因此点击时宽度变化会直接跳变,没有平滑效果。

修复方案

  1. 给.menu添加明确的初始宽度,比如width: fit-content(自适应文本宽度),或者固定像素值(如width: 120px)
  2. 将过渡时长从2s调整为你需要的0.5s

修正后的代码

CSS

@import url('https://fonts.googleapis.com/css2?family=Lato&family=Poppins:wght@500&family=Roboto:ital,wght@0,300;0,500;1,100;1,300&display=swap');

html{
    background: linear-gradient(45deg,#a12626 0%,#550bec 100%) no-repeat;
    height: 100%;
}

body{
    font-family: 'Poppins', sans-serif;
}

.container{
    position: relative;
    margin-top: 30%;
}

.menu{
    position: absolute;
    left: 50%;
    transform: translateX(-50%);
    background: linear-gradient(to right, #a12626 0%, #550bec 100%) no-repeat;
    box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px;
    padding: 10px 20px;
    border-radius: 50px;
    cursor: pointer;
    width: fit-content; /* 添加初始宽度 */
    transition: width 0.5s ease; /* 调整过渡时长为0.5秒 */
}

.menu.active{
    width: 300px;
}

JavaScript

var menu = document.querySelector('.menu');

menu.addEventListener('click', () => {
    menu.classList.toggle('active');
})

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <div class="container">
        <div class="menu">Menu</div>
    </div>
    <script src="script.js"></script>
</body>
</html>

说明

  • 使用width: fit-content可以让菜单初始宽度自适应文本内容,同时支持向固定宽度300px过渡
  • 过渡时长设置为0.5s,符合你需要的平滑速度
  • 元素的居中方式(left:50% + transform: translateX(-50%))会自动适应宽度变化,保持居中状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.26 04:15:29