固定位置后,为什么背景图像会消失?

时间:2020-08-02 22:32:01

标签: javascript css animation css-position

好的,我的目标是为背景图像设置动画,使其在页面加载时从底部向上滑动,并且一旦动画结束,将其位置设置为固定。据我所知,我编写的代码应该可以正常工作(虽然我很新),但是当动画结束并且javascript将position属性添加到背景图像时,它完全消失并且它下面的所有内容都向上移动取代它。有人可以告诉我我的代码有什么问题吗?

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'; };

2 个答案:

答案 0 :(得分:1)

在您的.background__img--英雄上,只需添加以下内容:

.background__img--hero {
    background-size: cover;
    background-position: center;
    height: 100vh;
    width: 100%;
    animation: slideUp 2s 1 ease-out forwards;
}

或您希望图像具有的任何宽度

答案 1 :(得分:0)

要对position:fixed元素的位置进行动画处理,请不要对 margins 进行动画处理,而要对位置本身进行动画处理(在此cas top中),就像

@keyframes slideUp {
    from {
        top: 700px;
    }
    to {
        top: 0px;
    }
}