I have a background and some pictures. Its auto playing but background images are not changing with transition effect. So it doesnt look well. Here my code. How can i add transition here?
var body = $("#banner");
var backgrounds = [
"url(./img/background/gorsel1.png)",
"url(./img/background/gorsel2.jpg)",
"url(./img/background/gorsel3.jpg)",
"url(./img/background/gorsel4.jpg)",
"url(./img/background/gorsel5.jpg)",
"url(./img/background/gorsel6.jpg)",
"url(./img/background/gorsel7.jpg)",
"url(./img/background/gorsel8.jpg)",
];
var current = 0;
$(function () {
var body = $("#banner");
function nextBackground() {
body.css({
"background-image":
"linear-gradient(to left, rgba(0, 0, 0, .6), transparent 27%), linear-gradient(to bottom, rgba(0, 0, 0, .6), transparent 27%), linear-gradient(to right, rgba(0, 0, 0, .6), transparent 27%)," +
backgrounds[(current = ++current % backgrounds.length)],
});
setTimeout(nextBackground, 5000);
}
setTimeout(nextBackground, 5000);
body.css({
"background-image":
"linear-gradient(to left, rgba(0, 0, 0, .6), transparent 27%), linear-gradient(to bottom, rgba(0, 0, 0, .6), transparent 27%), linear-gradient(to right, rgba(0, 0, 0, .6), transparent 27%)," +
backgrounds[0],
});
});
You have several issues in your code, both in javascript and in CSS. Use setInterval
instead of setTimeout because the latter just runs once. Since you're using jQuery a pratical way is to use fadeIn
and fadeOut
functions.
I slightly adapted your code on this running working example:
var backgrounds = [ "https://i.picsum.photos/id/866/200/300.jpg?hmac=rcadCENKh4rD6MAp6V_ma-AyWv641M4iiOpe1RyFHeI", "https://i.picsum.photos/id/793/200/300.jpg?grayscale&hmac=Iwryr2sIE-T3-CndRcI6YM0IffOLe7ovjimw6OzIzm8", "https://i.picsum.photos/id/1060/536/354.jpg?blur=2&hmac=0zJLs1ar00sBbW5Ahd_4zA6pgZqCVavwuHToO6VtcYY" ]; var current = 0; (function () { var body = $("#banner"); function nextBackground() { var url = `url(${backgrounds[(current = ++current % backgrounds.length)]})`; body.fadeOut("slow", () => { body.css({ "background-image": url, }); body.fadeIn("slow", () => { }); }); } nextBackground() setInterval(nextBackground, 5000); })();
#banner { width: 200px; height: 200px; border: 1px solid black; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="banner"></div>
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.