如何用CSS/JS实现悬停时充电电池式变色填充按钮?
实现充电电池填充效果的按钮(红色转绿色)
问题修正思路
你的现有代码逻辑是红色伪元素覆盖绿色按钮背景,和需求的「初始红色、hover时绿色逐步填充」完全相反,只需调整颜色层级和伪元素初始状态即可实现目标效果。
修改后的完整代码
CSS
.outer { margin: 50px; } .button { border: 1px solid black; border-radius: 3px; width: 100px; height: 30px; display: block; position: relative; overflow: hidden; background-color: red; /* 初始红色背景 */ cursor: pointer; } .button::before { content: ''; position: absolute; top: 0; left: 0; width: 0; /* 初始隐藏绿色填充层 */ height: 100%; background-color: green; transition: width 0.5s ease-out; /* 宽度过渡动画 */ } .button:hover::before { width: 100%; /* hover时填充整个按钮 */ } .text { text-align: center; font-size: 16px; line-height: 30px; color: black; transition: color 0.6s ease-out; display: block; position: relative; z-index: 1; /* 保证文字在填充层上方不被遮挡 */ } .button:hover .text { color: white; }
HTML
<div class="outer"> <button class="button"> <span class="text">Click me</span> </button> </div>
关键调整点
- 交换按钮与伪元素的背景色:按钮初始为红色,伪元素为绿色,实现hover时绿色逐步覆盖红色的填充效果
- 伪元素初始宽度设为0,hover时过渡到100%,模拟电池充电的填充动画
- 给文字添加
position: relative和z-index: 1,避免文字被填充层遮挡
内容的提问来源于stack exchange,提问作者gingg
相关产品推荐
相关产品推荐

