纯CSS实现按钮点击触发消失动画后元素永久隐藏的问题咨询
问题原因
你猜测的没错,问题确实出在:focus伪类上。:focus仅在元素持有焦点时生效,点击页面其他区域、再次点击按钮都会导致元素失去焦点,伪类匹配失效,按钮就会恢复原有样式。
纯CSS解决方案
用「隐藏复选框+label关联」的方案实现永久状态切换,复选框的:checked状态选中后不会自动消失,完美匹配你需要的「点击后永久消失」的需求。
修改后HTML代码
<!-- 隐藏的复选框,用来记录点击状态 --> <input type="checkbox" id="ghost1-check" hidden> <!-- label关联复选框,点击label就等于点击复选框 --> <label for="ghost1-check" class="ghost1" id="btn1">👻</label> <input type="checkbox" id="ghost2-check" hidden> <label for="ghost2-check" class="ghost2" id="btn2">👻</label>
修改后CSS代码
div { text-align: center; } .ghost1 { font-size: 14px; border-radius: 50px; border: none; background-color: transparent; /* 新增鼠标指针样式,提示可点击 */ cursor: pointer; } .ghost2 { font-size: 14px; border-radius: 50px; border: none; background-color: transparent; cursor: pointer; } @keyframes ghostDisappear { 0% { font-size: 14px; } 100% { font-size: 0px; } } /* 复选框选中时,相邻的label执行消失动画 */ #ghost1-check:checked + .ghost1 { animation-name: ghostDisappear; animation-duration: 0.2s; animation-fill-mode: forwards; animation-iteration-count: 1; } #ghost2-check:checked + .ghost2 { animation-name: ghostDisappear; animation-duration: 0.2s; animation-fill-mode: forwards; animation-iteration-count: 1; }
注:两个幽灵的消失动画逻辑一致,已经把重复的keyframes合并精简,后续新增更多幽灵只要重复「隐藏复选框+关联label」的结构,新增对应的CSS选择器即可。
内容的提问来源于stack exchange,提问作者F Tyrrell
相关产品推荐
相关产品推荐

