正如标题中提到的,我正在尝试更改滚动上的背景图像并轻松添加漂亮的过渡。
背景图像应该固定并保持在适当的位置。内容正在动。
有什么想法吗?
我设法更改图像,但转换不起作用。
<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>
是的,只有采用十进制值的 CSS 属性才可以设置动画。所以“不透明度”是可以设置动画的,但
background-image
则不能。
最简单的解决方案可能是堆叠多个图像并为其不透明度设置动画。