如何为侧边栏添加transition实现0.2s缓动的从左至右滑入效果?
实现侧边栏从左至右滑入的过渡效果
我需要实现点击汉堡菜单时,侧边栏从左至右滑入的效果,要求过渡属性为all 0.2s ease。我知道可以通过切换width为100%和0的方式实现,但想找其他替代方案。当前代码是通过切换display属性来显示/隐藏侧边栏,需要修改为带有过渡的滑入动画效果。
修改方案(无需改动JS和HTML)
核心思路是利用transform: translateX()替代display属性切换(display无法触发CSS过渡动画),具体CSS修改如下:
*{ margin:0; padding:0; list-style:none; box-sizing:border-box; text-decoration:none; } #sidebar-toggle{ display: inline-block; cursor: grab; background: rgba(0, 136,169, 1); border-radius: 50%; padding: 5px 10px; height: 40px; width: 40px; margin-top: 5px; } #sidebar-toggle div{ width: 20px; height: 2px; background-color: #fff; margin: 6px 0; transition: all 0.3s ease 0s; cursor: grab; } #sidebar-toggle.open .bar4 { transform: translate(0, 8px) rotate(-45deg); } #sidebar-toggle.open .bar5 { opacity: 0; } #sidebar-toggle.open .bar6 { transform: translate(0px, -8px) rotate(45deg); } /* 重点修改区域 */ .sidebar { position: fixed; height: 100vh; top: 50px; left: 0; background-color: #fff; width: 15.625rem; box-shadow: 0px 0px 2px 0px rgba(0, 0, 0, 0.75); /* 初始状态:将侧边栏移出视口左侧 */ transform: translateX(-100%); /* 添加要求的过渡效果 */ transition: all 0.2s ease; } .open.sidebar { /* 激活状态:让侧边栏回到原位置 */ transform: translateX(0); } /* 重点修改结束 */ .sidebar-nav{ position: absolute; margin: 0 0 0; width: 100%; padding: 5px 10px; } .sidebar-nav ul{ display: flex; flex-direction: column; justify-content:center; align-items: flex-start; } .sidebar-nav ul li { padding: 10px; color: #007bff; display: flex; flex-direction: column; } .sidebar-nav ul li:hover{ background: #007bff; color: #fff; } .sidebar-nav ul li a .icon{ color:#007bff; width:30px; display: inline-block; } .sidebar-nav .down_key{ margin-left: 50px; } .sidebar-nav ul li ul li{ display: flex; flex-direction: column; padding: 10px 20px; }
改动说明
- 移除
.sidebar的display:none,改用transform: translateX(-100%)隐藏侧边栏,避免display属性无法触发过渡的问题 - 给
.sidebar添加transition: all 0.2s ease,满足要求的过渡效果 - 将
.open.sidebar的display:flex替换为transform: translateX(0),触发滑入动画 - 保留原有固定定位、宽度等布局属性,确保侧边栏样式不变
内容的提问来源于stack exchange,提问作者user19171988
相关产品推荐
相关产品推荐

