如何为一个元素中的两个背景设置过渡



在此代码中:

#p1 {
background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
background-color: #05080d;
background-position: left top, left bottom;
background-size: 100% 35%, 100% 65%;
}

我希望当页面显示时,首先显示backimgs/first/1.jpg,然后在1秒后显示backimgs/first/2.jpg。我该怎么做?

不能设置背景图像的动画。你可以改变它,但不会有任何平稳的过渡:

#p1 {
background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
background-color: #05080d;
background-position: left top, left bottom;
background-size: 100% 35%, 100% 65%;
animation: change-bg;
animation-duration: 1s;
}
@keyframes change-bg {
0% {
background-image: url(backimgs/first/1.jpg), url(backimgs/first/2.jpg);
background-size: 100% 35%, 100% 65%;
}
100% {
background-image: url(backimgs/first/2.jpg), url(backimgs/first/1.jpg);
background-size: 100% 65%, 100% 35%;
}
}

如果想要平滑过渡,可以将::before::after与背景一起使用,并设置它们的不透明度动画。如果你需要更多关于这个过程的信息,请评论我,我会编辑帖子并展示它是如何完成的。

您在标题中提到了"transition",因此需要分别控制背景的两个部分。

为了实现这一点,这个片段从元素本身删除背景,而不是将它们放在两个伪元素上。具有第一图像作为背景的前伪元素和具有第二图像的后伪元素。

以这种方式分离组件意味着我们可以设置不透明度的动画,第一个伪元素在第一秒内从不透明度0变为不透明度1。

然而,请注意,这个片段中添加了一个小技巧。由于before伪元素上的动画将在加载时发生,因此需要有某种方法在动画开始之前等待背景图像加载,否则在图像实际可用之前,它可能会进行到一半,甚至完成。

我不知道你是如何测试负载完成的,所以为了演示的目的,我只是在这里放了一个延迟。您需要决定如何避免这种初始负载情况。

* {
margin: 0;
padding: 0;
}
#p1 {
/* added for this demo */
display: inline-block;
width: 100vw;
height: 100vh;
position: relative;
}
#p1::before,
#p1::after {
content: '';
position: absolute;
z-index: -1;
width: 100%;
left: 0;
display: inline-block;
background-color: #05080d;
background-size: cover;
background-repeat: no-repeat no-repeat;
background-position: center center;
animation: fadein 1s linear;
animation-fill-mode: forwards;
opacity: 0;
}
#p1::before {
top: 0;
height: 35%;
background-image: url(https://picsum.photos/id/1018/1024/768);
animation-delay: 1s;
/* a hack to ensure it is loaded before start the animation */
}
#p1::after {
bottom: 0;
height: 65%;
background-image: url(https://picsum.photos/id/1015/1024/768);
animation-delay: 2s;
}
@keyframes fadein {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
<div id="p1"></div>

最新更新