更改滚动上的固定背景图像

问题描述 投票:0回答:1

正如标题中提到的,我正在尝试更改滚动上的背景图像并轻松添加漂亮的过渡。

背景图像应该固定并保持在适当的位置。内容正在动。

有什么想法吗?

我设法更改图像,但转换不起作用。

<script>
document.addEventListener('DOMContentLoaded', function () {
    var backgroundContainer = document.querySelector('.background-container');

    // Add more images if you like.
    var backgroundImages = ['image1.jpg', 'image2.jpg'];


    var currentImageIndex = 0;

    // Set first background image
    backgroundContainer.classList.add('background-image-1');

    window.addEventListener('scroll', function () {
        // Check if you have scrolled to the top.
        var scrolledToTop = window.scrollY === 0;

        // Change backgroundclass
        if (scrolledToTop) {
            currentImageIndex = 0;
            backgroundContainer.classList.remove('background-image-2');
            backgroundContainer.classList.add('background-image-1');
        } else {
            currentImageIndex = 1;
            backgroundContainer.classList.remove('background-image-1');
            backgroundContainer.classList.add('background-image-2');
        }
      
    backgroundContainer.style.transition = 'background-image 1.5s ease';      
    });
});

</script>
javascript css background-image addeventlistener onscroll
1个回答
0
投票

是的,只有采用十进制值的 CSS 属性才可以设置动画。所以“不透明度”是可以设置动画的,但

background-image
则不能。

最简单的解决方案可能是堆叠多个图像并为其不透明度设置动画。

© www.soinside.com 2019 - 2024. All rights reserved.