简体   繁体   English

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

[英]Changing background-images with a fade inbetween

I'm trying to change the background images of my hero section with JS.我正在尝试用 JS 更改我的英雄部分的背景图像。 The loop is working but I'm not sure how to have one image fade into the next.循环正在工作,但我不确定如何让一张图像淡入下一张。

The way that it is currently set up makes it fade to white (the background colour) inbetween changes, rather than fading from one image to the next.当前设置的方式使其在更改之间淡化为白色(背景色),而不是从一个图像淡化到下一个图像。

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

One thing you could do is use absolute positioning on the .hero elements.您可以做的一件事是在.hero元素上使用绝对定位。 Every time you want to change the background, you can then insert a new .hero with display:none on top of the old .hero .每次您想更改背景时,您都可以在旧的.hero之上插入一个带有display:none的新.hero For absolute positioning to work you can add a container with position:relative .要使绝对定位起作用,您可以添加一个带有position:relative的容器。 That way, you can be sure that all the .hero elements are at the exact same position.这样,您可以确定所有.hero元素都在完全相同的 position 中。 So your html and css could look like this:因此,您的 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>

Now, using javascript, you can add a .hero to the container, which will show on top.现在,使用 javascript,您可以将.hero添加到容器中,它将显示在顶部。 Since we want it to fade, we first set display to none, then fade it in. After fading in we can remove the old .hero .由于我们希望它淡出,我们首先将display设置为 none,然后将其淡入。淡入后我们可以删除旧的.hero Something like this:像这样的东西:

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();
    });
};

Does that come close to what you need?这是否接近您的需要?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM