我正在使用一个简单的jQuery来旋转(并随机化)一系列图像。我想知道调整它来旋转通过类定义的背景图像将有多么困难。
该脚本如下所示:
<script type="text/javascript">
jQuery.jQueryRandom = 0;
jQuery.extend(jQuery.expr[":"],
{
random: function(a, i, m, r) {
if (i == 0) {
jQuery.jQueryRandom = Math.floor(Math.random() * r.length);
};
return i == jQuery.jQueryRandom;
}
});
$(function() {
$('#slideshow img').not(':random').hide(); //hide all images except one initially
setInterval(function(){
$('#slideshow img:visible').fadeOut('slow')
.siblings('img:random').fadeIn('slow') //find a random image
.end().appendTo('#slideshow');},
9000); //2 second interval
});
</script>
HTML是:
<div id="slideshow">
<img src="banner1.jpg" />
<img src="banner2.jpg" />
<img src="banner3.jpg" />
<img src="banner4.jpg" />
<img src="banner5.jpg" />
</div>
的CSS
<style type="text/css">
#slideshow {
width: 100%;
position: relative;
}
#slideshow img {
top: 0;
left: 0;
width: 100%;
height: auto;
position: absolute;
}
</style>
因此,我想做的,但无法弄清楚的是,图像是否作为应用于班级的背景旋转。因此,与其在html中定义所有图片,不如在此类中旋转:
.slideshow {
background: url(banner1.jpg) no-repeat bottom center;
}
通过对上面的脚本进行一些调整,是否有可能?这种方法有什么陷阱吗?
谢谢!
使用与引用元素相反的URL数组,然后使用jQuery的URL将其应用于背景.css
。看起来像这样
var imgArray = ['banner1.jpg',
'banner2.jpg',
'banner3.jpg',
'banner4.jpg',
'banner5.jpg'
]
var nextBG = "url(" + imgArray[Math.floor(Math.random() * imgArray.length)] + ") no-repeat bottom center";
$('#slideshow').css("background", nextBG);
setInterval(function(){
nextBG = "url(" + imgArray[Math.floor(Math.random() * imgArray.length)] + ") no-repeat bottom center";
$('#slideshow').fadeOut('slow', function() {
$(this).css("background", nextBG).fadeIn('slow'); })
}, 3000); // 3 second interval
如果您希望有多个幻灯片放映,那将是相同的,但是您可以将ID更改为一个类,然后使用aforEach
或.slideshow:eq(0)
对每个幻灯片进行操作。您还必须第二次生成随机图像。如果您正在寻找这个,请告诉我
但是,要做到这一点,它要比看起来复杂得多,最好是事先加载图像。您可以将它们加载到如本文所述的隐藏元素中,也可以使用jQuery像其他文章中所述的那样预加载它们
编辑:第一次发布时,我不小心$('#slideshow img')
从原来的内容中获得了更改。突然出现在之前fadeOut
是由于.css
未在后面排队.fadeOut
,因此我通过在的回调函数中更改背景网址来解决了该问题fadeOut
如果您不希望在同一图像出现后立即重复显示,可以将当前图像在图像数组中的位置与下一图像在图像数组中的位置进行比较。 setInterval
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句