本文介绍了动态更改CSS背景图片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我已经尝试了一些事情,但到目前为止没有运气。
I have tried a couple things already but so far no luck.
我要找的是一种方法,使我的HTML标题标签每几秒钟更换背景图片。欢迎任何解决方案,只要它不复杂。
What I'm looking for is a way to make my HTML header tag change background images every few seconds. Any solutions are welcome, as long as it is not to complex.
我现在有这个代码,以及链接到JQuery:
I have this code right now as well as linking to JQuery:
< script src =http://code.jquery.com/jquery-latest.min.jstype =text / javascript>< / script> ;
$(function() {
var header = $(‘.mainHeader’);
var backgrounds = new Array(
‘url(img/rainbow.jpg)’,
‘url(img/chickens_on_grass.jpg)’
‘url(img/cattle_on_pasture.jpg)’
‘url(img/csa_bundle.jpg)’
);
var current = 0;
function nextBackground() {
header.css(‘background’,backgrounds[current = ++current % backgrounds.length]);
setTimeout(nextBackground, 10000);
}
setTimeout(nextBackground, 10000);
header.css(‘background’, backgrounds[0]);
});
我的HTML标题:
< header class =mainHeader>< / header>
和CSS:
.mainHeader {
background: no-repeat center bottom scroll;
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
min-height: 150px;
padding-top: 2%;
font-size: 100%;
}
现在我已经有了背景图片。
Right now I have now background image at all.
期待收到建议。
推荐答案
<html>
<head>
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(document).ready(function(){
var header = $('body');
var backgrounds = new Array(
'url(http://placekitten.com/100)'
, 'url(http://placekitten.com/200)'
, 'url(http://placekitten.com/300)'
, 'url(http://placekitten.com/400)'
);
var current = 0;
function nextBackground() {
current++;
current = current % backgrounds.length;
header.css('background-image', backgrounds[current]);
}
setInterval(nextBackground, 1000);
header.css('background-image', backgrounds[0]);
});
</script>
</head>
<body>
<header></header>
</body>
</html>
这篇关于动态更改CSS背景图片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!