简体   繁体   中英

Smooth Transition Between Background Images

So, I made this script where the background changes the farther you scroll down the page, but I want it so there is a transition between each of the images. So when you scroll from one image to the next, it slowly fades into the next. Sort of like a parallax.

JS:

$(document).ready(function() {
  $("body ").css("background-image", "url('http://i.imgur.com/rs2Ittp.jpg')");
  $(window).scroll(function() {
    if($(this).scrollTop() > 0) {
     $("body ").css("background-image", "url('http://i.imgur.com/rs2Ittp.jpg')");
    }
    if($(this).scrollTop() > 1000) {
      $("body ").css("background-image", "url('http://i.imgur.com/H5QLuD6.jpg')");
    }
    if($(this).scrollTop() > 2000) {
      $("body ").css("background-image", "url('http://i.imgur.com/KzZpgdS.jpg')");
    }
    if($(this).scrollTop() > 3000) {
     $("body ").css("background-image", "url('http://i.imgur.com/UsLLJSx.jpg')");
    }
  });
});

Any solutions are appreciated (:

The easiest solution is through CSS:

body {
    transition: background-image 0.5s ease-in-out;
}

Edit: My answer may have been a bit premature, since this is not a cross-browser solution. A better way to do this would be by using two divs with different background images using transition: opacity 0.5s; A lot more javascript is involved in this solution though.

Here's one way of doing it. Create two elements with position: fixed , then change the opacity as you scroll. Once you get over a certain scroll position, swap the next images in and use the same opacity logic minus the intended scroll length.

edit: my opacity math could be more refined + need to add swapping the images back when scrolling the reverse direction

<!-- html -->
<div class="bottom"></div>
<div class="top"></div>

/* css */
.bottom,
.top {
  position: fixed;
  background-size: cover;
  height: 100%;
  width: 100%;
}

// js
var img1 = 'url(http://i.imgur.com/rs2Ittp.jpg)'
  , img2 = 'url(http://i.imgur.com/H5QLuD6.jpg)'
  , img3 = 'url(http://i.imgur.com/KzZpgdS.jpg)'

$(document).ready(function() {
  $('.top').css("background-image", img1)
  $('.bottom').css("background-image", img2)

  $(window).scroll(function() {
    var scrollTop = $(this).scrollTop()

    if (scrollTop < 1000) {
      $('.top').css('opacity', 100 / scrollTop)
    }

    else if ($(this).scrollTop() > 1000) {
      $('.top').css("background-image", img2)
      $('.bottom').css("background-image", img3)
      $('.top').css('opacity', 100 / (scrollTop - 1000))
    }
  })
})

codepen

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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