设置animation-fill-mode: forwards后文本动画状态无法保留的问题咨询
解决CSS动画结束后文本消失的问题
嘿,我看到你已经尝试用animation-fill-mode: forwards来保留动画结束后的状态,但还是遇到了文本消失的问题,咱们来看看哪里出问题了~
问题根源
你的@keyframes from_left_to_bottom里,100%的帧只定义了opacity: 1,但没有设置top属性:
- 虽然你在75%的帧里把
top设为了250px,但动画到100%时,因为没有指定top,元素会回到它的初始样式(.from_left_to_bottom类里没定义top,所以top会变成auto)。 - 再加上父容器
.gran_slider_big_item_container设置了overflow: hidden,当top变成auto时,元素直接被移出了可视区域,看起来就像消失了。
另外还有个小细节:@keyframes里重复写position: absolute完全没必要,因为元素本身已经在类里设置了这个属性,删掉它能让代码更简洁。
修复后的代码
只需要在100%帧里补上top: 250px,同时顺手修复一个样式分号缺失的小问题:
.from_left_to_bottom { position: absolute; left: 120px; opacity: 1; animation-name: from_left_to_bottom; animation-delay: 1500ms; animation-duration: 6s; animation-fill-mode: forwards; -moz-animation-fill-mode: forwards; animation-iteration-count: 1; z-index:9999; } @keyframes from_left_to_bottom { 0% { top: -200px; opacity: 0; } 75% { top: 250px; opacity: 1; } 100% { top: 250px; /* 新增这行,强制保持动画结束后的位置 */ opacity: 1; } } /*GRAN SLIDER START*/ .gran_slider_maincontainer{width:100%; height:100vh; display:flex; flex-direction:column; overflow:hidden;} .gran_slider_big_container{width:100%; position:relative; height:90vh; overflow:hidden;} .gran_slider_big_navegation_container{width:auto; height:30px; display:flex; align-items:center; position:absolute; bottom:25px; right:50px; z-index:10000;} .gran_slider_big_navegation_dot{width:15px; height:15px; background-color:rgba(255,255,255,0.4); margin:0px 3px; border-radius:50%;} .gran_slider_big_item_container{width:100%; height:100%; position:relative; overflow:hidden;} .gran_slider_big_item_gradient_overlay{width:100%; height:100%; z-index:3; background-color:rgba(0,0,0,0.3); position:absolute; top:0px; left:0px;} .gran_slider_big_item_image{width:100%; height:100%; z-index:2; background-position:center; background-size:cover;} .gran_slider_big_item_texts_container{width:55%; height:auto; display:flex; flex-direction:column; padding:10px;} .gran_slider_big_item_texts_title{font-size:45px; color:white; font-weight:600; margin-bottom:30px; text-shadow:5px 5px 10px rgba(0,0,0,1.0);} .gran_slider_big_item_texts_description{font-size:30px; color:white; font-weight:600; margin-bottom:30px; text-shadow:5px 5px 10px rgba(0,0,0,1.0);} /* 补上缺失的分号 */ .gran_slider_small_container{width:100%; height:10vh; background: linear-gradient(to bottom, rgba(0, 0, 0, 0.9), rgba(0, 0, 0, 0));} /*GRAN SLIDER END*/
为什么这样有效?
animation-fill-mode: forwards的作用是让元素在动画结束后保持最后一帧的样式,但如果最后一帧没有定义某个属性,浏览器就会回到元素的初始样式。现在我们在100%帧里明确设置了top:250px,动画结束后元素就会一直保持这个位置,不会再“消失”了。
内容的提问来源于stack exchange,提问作者user8749260
相关产品推荐
相关产品推荐

