简体   繁体   中英

Fade In and Fade Out Within a Search Interval Function

I've written a function that empties a div and inserts a random image from unsplash.com every six seconds using the setInterval function in jQuery. I would like to smooth out the transition using the fadeIn and fadeOut functions, but have been unable to successfully implement this. Below is my code:

function playImageSlideshow() {
  $("#image-slideshow").removeClass("display-none");
  $("#images").append("<img src = 'https://source.unsplash.com/" + currentCity + "'>");
  setInterval(function() {
    var date = new Date();
    $("#images").empty();
    $("#images").append("<img src = 'https://source.unsplash.com/" + currentCity + "/?" + date.getTime() + "'>");
  }, 6000);
}

Use the function fadeIn from jQuery.

First Create the img element as follow:

var $img = $("<img class='hide' src = 'https://source.unsplash.com/" + currentCity + "/?" + date.getTime() + "'>");

Then, call the faIn function:

$img.fadeIn()

That img is created with a class hide to hide it and then execute the fadeIn effect. Another alternative is execute the hide() function before append this new elemento to your DIV , ie: $img.hide() .

Look at this code snippet

 let currentCity = 'london'; function playImageSlideshow() { $("#image-slideshow").removeClass("display-none"); $("#images").append("<img src = 'https://source.unsplash.com/" + currentCity + "'>"); setInterval(function() { var date = new Date(); var $images = $("#images"); $("#images img").fadeOut(1000, function() { $images.empty(); var $img = $("<img class='hide' src = 'https://source.unsplash.com/" + currentCity + "/?" + date.getTime() + "'>"); $images.append($img); $img.fadeIn(2000); }); }, 3000); } playImageSlideshow(); 
 .hide { display: none } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='images'></div> 

See? now the transition is smoother.

Resource

Just use the JQuery API and update the image in the setTimeout.

 setInterval(function() { $("#images").fadeOut(1000); $("#images").attr("src", "https://i2.wp.com/www.monicaperezcounseling.com/wp-content/uploads/2017/01/pexels-source-unsplash-4.jpg"); $("#images").fadeIn(1000); }, 2000); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <img id="images"/> 

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