使用jQuery更改背景图像 [英] background Image change using jquery
本文介绍了使用jQuery更改背景图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在从此代码更改背景图像
I am changing my background image from this code
jQuery(window).load(function(){
var images = ['blaa.jpg','sdsd.jpg'];
var i = 0;
setInterval(function(){
jQuery('#absolute-c').css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
}, 3000);
})
.animate
的操作方法并立即加载第一背景。由于 setInterval
,我的第一个背景也会在3秒后显示
how do .animate
and load first background without delay. due to setInterval
my first background also show after 3 sec
推荐答案
您可以为此创建一个函数并在setInterval中使用它:
You can do create a function for this and use it in the setInterval:
jQuery(window).load(function(){
var images = ['blaa.jpg','sdsd.jpg'];
var i = 0;
function changeBackground() {
jQuery('#absolute-c').css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
}
// Call it on the first time
changeBackground();
// Set an interval to continue
setInterval(changeBackground, 3000);
});
另一种解决方案(我认为更好)是使用 setTimeout
代替:
Another solution, and I think is much better, is to use setTimeout
instead:
jQuery(window).load(function(){
var images = ['blaa.jpg','sdsd.jpg'];
var i = 0;
var timeoutVar;
function changeBackground() {
clearTimeout(timeoutVar); // just to be sure it will run only once at a time
jQuery('#absolute-c').css('background-image', function() {
if (i >= images.length) {
i=0;
}
return 'url(' + images[i++] + ')';
});
// call the setTimeout every time to repeat the function
timeoutVar = setTimeout(changeBackground, 3000);
}
// Call it on the first time and it will repeat
changeBackground();
});
这篇关于使用jQuery更改背景图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文