动画-菜单按钮
2023/6/16大约 3 分钟
这是一个使用 HTML 和 CSS 实现的动画菜单按钮效果,通过悬停交互将三条横线转变为 "X" 形状,常用于移动端导航菜单的开关按钮。
效果展示
<div class="container">
<div class="btn-case">
<span class="line"></span>
<span class="line"></span>
<span class="line"></span>
</div>
</div>
.container {
position: relative;
height: 40px;
width: 100%;
display: flex;
justify-content: center;
}
.btn-case {
width: 48px;
height: 36px;
display: block;
position: relative;
cursor: pointer;
}
.btn-case .line {
width: inherit;
height: 4px;
border-radius: 2px;
display: block;
background-color: #3d3d3d;
position: absolute;
top: 0;
transition: all 0.2s ease-in-out;
}
.btn-case .line:nth-of-type(2) {
top: 16px;
}
.btn-case .line:nth-of-type(3) {
top: 32px;
}
.btn-case:hover .line:nth-of-type(1) {
transform: rotate(45deg);
top: 16px;
}
.btn-case:hover .line:nth-of-type(2) {
width: 0;
}
.btn-case:hover .line:nth-of-type(3) {
transform: rotate(-45deg);
top: 16px;
}
代码解析
HTML 结构
这个动画菜单按钮的 HTML 结构非常简洁,主要由三层组成:
- 最外层的
container
div 用于居中显示按钮 - 中间层的
btn-case
div 作为按钮的容器 - 内层的三个
line
span 元素构成了按钮的三条横线
通过简单的嵌套结构,我们就可以实现一个标准的汉堡菜单按钮布局。
CSS 动画原理
这个动画效果主要依靠 CSS 的 transition
和 transform
属性实现:
初始状态设置:
- 三条横线通过
position: absolute
定位在不同的垂直位置 - 设置了
transition: all 0.2s ease-in-out
使变化过程平滑过渡
- 三条横线通过
悬停效果:
- 第一条横线旋转 45 度并移动到中间位置
- 第二条横线宽度变为 0,实现隐藏效果
- 第三条横线旋转 -45 度并移动到中间位置
- 最终三条横线组合成 X 形状
这种交互设计直观地向用户传达了 "关闭" 的语义,同时通过平滑的动画效果提升了用户体验。
使用方法
自定义样式
你可以根据需要调整以下样式参数:
- 尺寸调整:修改
.btn-case
的width
和height
属性 - 颜色调整:修改
.line
的background-color
属性 - 线条粗细:修改
.line
的height
属性 - 动画速度:修改
transition
的时间值
完整示例
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>动画菜单按钮</title>
<style>
.btn-case {
width: 48px;
height: 36px;
display: block;
position: relative;
cursor: pointer;
}
.btn-case .line {
width: inherit;
height: 4px;
border-radius: 2px;
display: block;
background-color: #3d3d3d;
position: absolute;
top: 0;
transition: all 0.2s ease-in-out;
}
.btn-case .line:nth-of-type(2) {
top: 16px;
}
.btn-case .line:nth-of-type(3) {
top: 32px;
}
.btn-case:hover .line:nth-of-type(1) {
transform: rotate(45deg);
top: 16px;
}
.btn-case:hover .line:nth-of-type(2) {
width: 0;
}
.btn-case:hover .line:nth-of-type(3) {
transform: rotate(-45deg);
top: 16px;
}
</style>
</head>
<body>
<div class="container">
<div class="btn-case">
<span class="line"></span>
<span class="line"></span>
<span class="line"></span>
</div>
</div>
</body>
</html>
注意事项
- 浏览器兼容性:所有主流现代浏览器都支持此功能
- 性能考虑:动画效果简单,对性能影响较小
更新日志
2025/9/28 09:03
查看所有更新日志
38e56
-于