简体   繁体   English

如何在计时器上更改背景图像

[英]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. 我想知道如何通过淡入/淡出过渡使背景图像每5秒更改一次。 Sorry if this seems like a newbie question but I'm just starting out learning Js/Jquery. 抱歉,如果这似乎是一个新手问题,但我刚开始学习Js / Jquery。

My second question would be is it possible to do this using pure CSS3 or would js/jquery work better? 我的第二个问题是有可能使用纯CSS3做到这一点,还是js / jquery更好?

Many thanks, Aidan 非常感谢,艾丹

I have created a test case for you using jquery: https://codebrace.com/editor/afec3e661 我已经使用jquery为您创建了一个测试用例: https : //codebrace.com/editor/afec3e661

With pure js you may replace jquery with document.body.style.backgroundImage = "url('" + a[i++] + "')"; 使用纯js,您可以将jquery替换为document.body.style.backgroundImage =“ url('” + a [i ++] +“')”;

Test case for background change with fadein/out effect: https://codebrace.com/editor/afef034d6 具有淡入/淡出效果的背景变化的测试用例: https ://codebrace.com/editor/afef034d6

You can't make fade-in fade-out animation on background-image , because this atribute cannot be animated. 您无法在background-image上制作fade-in fade-out动画,因为无法对该属性进行动画处理。 Instead of it, you can make 2 fixed elements which are positioned over each other. 取而代之的是,您可以将2个固定的元素放置在彼此上方。

You can't make timeout/interval in plain CSS, you'll have to use JS. 您不能在普通CSS中设置超时/间隔,而必须使用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/ 我使用过setInterval函数来切换两个元素的.active状态,类.active通过transition添加到元素opacity -示例在这里: https : .active

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

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