首页 > 解决方案 > 使用淡入淡出改变背景图像

问题描述

我正在尝试用 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);
  });

标签: javascriptjquerycss

解决方案


您可以做的一件事是在.hero元素上使用绝对定位。每次你想改变背景时,你可以在旧.hero的. 要使用绝对定位,您可以添加一个带有. 这样,您可以确保所有元素都位于完全相同的位置。所以你的 html 和 css 可能看起来像这样:display:none.heroposition:relative.hero

<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,您可以将 a 添加.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();
    });
};

这是否接近您的需要?


推荐阅读