使用淡入淡出更改背景图像

时间:2021-04-27 16:21:17

标签: javascript jquery css

我正在尝试使用 JS 更改我的英雄部分的背景图像。循环正在运行,但我不确定如何让一个图像淡入下一个。

它当前的设置方式使其在变化之间淡化为白色(背景颜色),而不是从一个图像淡化到下一个。

var images = ["../images/winter.jpeg", "../images/spring.jpeg", "../images/summer.jpeg", "../images/welcome.jpeg"];
var index = 0;

function changeBackground() {

  index = (index + 1 < images.length) ? index + 1 : 0;

  $('.hero').fadeOut(0, function () {

    $(this).css('background-image', 'url(' + images[index] + ')')

    $(this).fadeIn(0);

  });
};

var timer = null;

function startSetInterval() {
  timer = setInterval(changeBackground, 2000);
}
// start function on page load
startSetInterval();

$('.link-block-animation').hover(
  function () {
    clearInterval(timer);
  },
  function () {
    timer = setInterval(changeBackground, 2000);
  });

1 个答案:

答案 0 :(得分:1)

您可以做的一件事是在 .hero 元素上使用绝对定位。每次您想要更改背景时,您都可以在旧的 .hero 之上插入一个带有 display:none 的新 .hero。为了使绝对定位起作用,您可以使用 position:relative 添加一个容器。这样,您可以确保所有 .hero 元素都位于完全相同的位置。所以你的 html 和 css 可能是这样的:

<style>
.container{
    position:relative;
    height:100px;
    width:100px;
}
.hero{
    position:absolute;
    top:0;
    left:0;
    bottom:0;
    right:0;
}
</style>
<div class="container">
    <div class="hero"></div>
</div>

现在,使用 javascript,您可以向容器添加一个 .hero,它将显示在顶部。由于我们希望它淡出,我们首先将 display 设置为 none,然后将其淡入。淡入后,我们可以删除旧的 .hero。像这样:

var index = 0;

$('.hero').css('background-image', 'url(' + images[index] + ')');

function changeBackground() {
    var oldHero = $('.hero');
    var newHero = $('<div class="hero"></div>');
    index = (index + 1 < images.length) ? index + 1 : 0;
    newHero.css('display','none');
    newHero.css('background-image', 'url(' + images[index] + ')');
    $('.container').append(newHero);
    newHero.fadeIn(1000,function(){
        oldHero.remove();
    });
};

这是否接近您的需要?