简体   繁体   中英

How to make a background image change on timer

I have a simple full screen background image as shown below:

body {
 /* The background image used */
 background-image: url("../images/bg-one.jpg");

 /* Full height */
 height: 100vh; 
 width: 100vw;

 /* Hide scroll */
 overflow-x: hidden;
 overflow-y: hidden;

 /* Center and scale the background image nicely */
 background-position: center;
 background-repeat: no-repeat;
 background-size: cover;
}

I would like to know how I can make the background image change every 5 seconds with a fade in/out transition. Sorry if this seems like a newbie question but I'm just starting out learning Js/Jquery.

My second question would be is it possible to do this using pure CSS3 or would js/jquery work better?

Many thanks, Aidan

I have created a test case for you using jquery: https://codebrace.com/editor/afec3e661

With pure js you may replace jquery with document.body.style.backgroundImage = "url('" + a[i++] + "')";

Test case for background change with fadein/out effect: https://codebrace.com/editor/afef034d6

You can't make fade-in fade-out animation on background-image , because this atribute cannot be animated. Instead of it, you can make 2 fixed elements which are positioned over each other.

You can't make timeout/interval in plain CSS, you'll have to use JS. I've used setInterval function which is switching .active state of two elements, class .active adds to element opacity with transition - example is here: https://jsfiddle.net/2cxmeq7p/

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