如何使用CSS实现鼠标悬停时填充SVG path并添加动画效果
实现方案
这个效果直接用CSS控制SVG的描边属性就能实现,不用写JS,具体操作如下:
1. 调整SVG结构
在原有路径的基础上新增一条完全相同的路径作为动画层,用来模拟填充效果:
<button class="custom-btn"> <svg width="22" height="42" viewBox="0 0 22 42" fill="none" xmlns="http://www.w3.org/2000/svg" > <!-- 原有基础描边路径 --> <path d="M1 41C12.0457 41 21 32.0457 21 21C21 9.9543 12.0457 1 1 1" stroke="#00A9E0" stroke-width="2" stroke-linecap="round" /> <!-- 新增动画填充路径 --> <path class="fill-animation" d="M1 41C12.0457 41 21 32.0457 21 21C21 9.9543 12.0457 1 1 1" stroke="#00A9E0" stroke-width="20" stroke-linecap="round" stroke-dasharray="63" stroke-dashoffset="63" fill="none" /> </svg> </button>
2. 添加CSS样式
给按钮和动画路径加上交互和过渡效果:
.custom-btn { border: none; background: transparent; padding: 10px; cursor: pointer; } .fill-animation { opacity: 0; transition: all 0.3s ease-in-out; } .custom-btn:hover .fill-animation { stroke-dashoffset: 0; opacity: 1; }
效果说明
- 动画层的描边宽度设为20,刚好能填满整个C形区域,用描边模拟填充效果,不需要修改原路径的闭合属性。
stroke-dasharray的值和当前路径总长度(约63px)一致,初始stroke-dashoffset设为相同值,让动画路径默认完全隐藏,hover时偏移归零就会产生从下到上逐步填充的动效。- 可以根据需求调整transition的时长修改动画速度,或者修改动画路径的stroke值更换填充颜色。
内容的提问来源于stack exchange,提问作者H.sha
相关产品推荐
相关产品推荐

