为什么固定位置后背景图片会消失?
Why does my background image disappear when I make its position fixed?
好的,我的目标是在页面加载时使背景图像从底部向上滑动并在动画结束后将其位置设置为固定。据我所知,我编写的代码应该可以完美运行(虽然我很新),但是当动画结束并且 javascript 将位置 属性 添加到背景图像时,它完全消失,它下面的所有东西都会向上移动取代它的位置。谁能告诉我我的代码有什么问题吗?
HTML:
<div style="background-image: url(/resources/css/img/Logo\ Cropped.jpg);" class="background__img--hero"></div>` (set inside the header)
CSS:
@keyframes slideUp {
from {
margin-top: 700px;
}
to {
margin-top: 0px;
}
}
.background__img--hero {
background-size: cover;
background-position: center;
height: 100vh;
animation: slideUp 2s ease-out;
}
Javascript:
document.querySelector('.background__img--hero').addEventListener('animationend', posFix);
function posFix() { document.querySelector('.background__img--hero').style.position = 'fixed'; };
在您的 .background__img--hero,只需添加这些:
.background__img--hero {
background-size: cover;
background-position: center;
height: 100vh;
width: 100%;
animation: slideUp 2s 1 ease-out forwards;
}
或您希望图像具有的任何宽度
要对 position:fixed
元素的位置进行动画处理,请不要对 边距 进行动画处理,而是对位置本身进行动画处理(在本例 top
中),喜欢
@keyframes slideUp {
from {
top: 700px;
}
to {
top: 0px;
}
}
好的,我的目标是在页面加载时使背景图像从底部向上滑动并在动画结束后将其位置设置为固定。据我所知,我编写的代码应该可以完美运行(虽然我很新),但是当动画结束并且 javascript 将位置 属性 添加到背景图像时,它完全消失,它下面的所有东西都会向上移动取代它的位置。谁能告诉我我的代码有什么问题吗?
HTML:
<div style="background-image: url(/resources/css/img/Logo\ Cropped.jpg);" class="background__img--hero"></div>` (set inside the header)
CSS:
@keyframes slideUp {
from {
margin-top: 700px;
}
to {
margin-top: 0px;
}
}
.background__img--hero {
background-size: cover;
background-position: center;
height: 100vh;
animation: slideUp 2s ease-out;
}
Javascript:
document.querySelector('.background__img--hero').addEventListener('animationend', posFix);
function posFix() { document.querySelector('.background__img--hero').style.position = 'fixed'; };
在您的 .background__img--hero,只需添加这些:
.background__img--hero {
background-size: cover;
background-position: center;
height: 100vh;
width: 100%;
animation: slideUp 2s 1 ease-out forwards;
}
或您希望图像具有的任何宽度
要对 position:fixed
元素的位置进行动画处理,请不要对 边距 进行动画处理,而是对位置本身进行动画处理(在本例 top
中),喜欢
@keyframes slideUp {
from {
top: 700px;
}
to {
top: 0px;
}
}