在页面加载时对背景图像应用不透明度淡出动画



我想让背景图像的不透明度从不可见渐变到50%,并保持在那里。

这里有一个类似的问题,但是我没有跟上,看起来很复杂。也许它会帮助到有类似问题的人。

我只是想使用CSS,如果可能的话,没有JS。这是我目前在style.css:

中的内容
body {
background-image: url("img/me.png");
background-color: #cccccc;
background-repeat: no-repeat;
background-position: top;
background-attachment: fixed;
animation: fadeInBG 5s; 
}
@keyframes fadeInBG {
0% { opacity: 0.0; }
100% { opacity: 0.5; }
}

您将需要将图像url更改为其他内容以进行测试。现在,它将动画应用于整个页面主体(包括页面上的任何文本),根本不触及背景,背景总是100%没有动画。html文件中的简单文本是:

<h1> Hello world! </h1>

…它做动画。如何将动画逻辑只指向背景图像?我希望你能指定body.background-image而不是body,这样问题就解决了。

我注意到的另一件事是,一旦动画完成,文本"跳跃";到100%不透明度,它不会像我上面设置的那样保持在50%。如何解决这个问题?

在你的CSS代码中添加下面的代码。

body {
animation-fill-mode: forwards;
}

有用链接:https://developer.mozilla.org/en-US/docs/Web/CSS/animation-fill-mode

另外,我建议您添加一个div来实现它。

.bg-img {
background-image: url("https://media.istockphoto.com/photos/ginger-cat-portrait-picture-id1290233518?b=1&k=20&m=1290233518&s=170667a&w=0&h=C-eVqPpxcxCFqJsykl4rTzq0Kl995ZHCaLB9BgSgEzk=");
background-color: #cccccc;
background-repeat: no-repeat;
background-position: top;
background-attachment: fixed;
animation: fadeInBG 5s;
/* add */
animation-fill-mode: forwards;
position: fixed;
inset: 0;
z-index: -1;
}
@keyframes fadeInBG {
0% {
opacity: 0;
}
100% {
opacity: 0.5;
}
}
<h1> Hello world! </h1>
<div class="bg-img"></div>

最新更新