CSS代码中animate2动画失效问题排查求助
问题排查:CSS animate2动画无法触发的原因与修复
嘿,我仔细瞅了你的代码,一下子就找到问题所在了——你只定义了a:before的基础伪元素样式,完全没给a:after设置初始样式!浏览器没法识别一个不存在的伪元素,自然也就没法执行animate2动画啦。
错误原因
伪元素:after必须先具备基础的定位、尺寸、边框等初始属性,才能成为动画的载体。你给:before写了完整的初始设置,但:after没有任何定义,所以即使在hover时触发了动画,也没有元素来执行它。
修复后的完整代码
body{ margin:0; padding:0; background-color:#f1ff36; font-family:verdana; } .center{ position:absolute; top:50%; left:50%; transform:translate(-50%,-50%); } a{ position:relative; text-decoration:none; border:2px solid transparent; width:100px; height:50px; text-align:center; line-height:50px; display:inline-block; font-size:24px; color:#262626; } /* 定义:before的初始样式 */ a:before{ content:''; position:absolute; top:-2px; left:-2px; width:0; height:0; background:transparent; border:2px solid transparent; } /* 关键:添加:after的初始样式,和:before对应 */ a:after{ content:''; position:absolute; bottom:-2px; right:-2px; width:0; height:0; background:transparent; border:2px solid transparent; } a:hover:before{ animation:animate 1s linear forwards; } @keyframes animate{ 0%{ width:0; height:0; border-top-color:#262626; border-right-color:transparent; border-bottom-color:transparent; border-left-color:transparent; } 50%{ width:100%; height:0; border-top-color:#262626; border-right-color:#262626; border-bottom-color:transparent; border-left-color:transparent; } 100%{ width:100%; height:100%; border-top-color:#262626; border-right-color:#262626; border-bottom-color:transparent; border-left-color:transparent; } } a:hover:after{ animation:animate2 1s linear forwards; animation-delay:1s; } @keyframes animate2{ 0%{ width:0; height:0; border-top-color:transparent; border-right-color:transparent; border-bottom-color:transparent; border-left-color:#262626; } 50%{ width:0; height:100%; border-top-color:transparent; border-right-color:transparent; border-bottom-color:#262626; border-left-color:#262626; } 100%{ width:100%; height:100%; border-top-color:transparent; border-right-color:transparent; border-bottom-color:#262626; border-left-color:#262626; } }
额外说明
我把:after的初始位置设为bottom:-2px; right:-2px,这样它的动画会从右下角开始,和:before的左上角动画形成对称效果,完美匹配你写的animate2关键帧逻辑。现在你再测试一下,animate2应该能正常触发了!
内容的提问来源于stack exchange,提问作者GeekyGautam
相关产品推荐
相关产品推荐

