我在编写一组特定的函数时遇到了麻烦。我正在为响应式网站制作视觉赞助商栏。我有大约 20 个赞助商徽标,分为 5 个 div,我需要随机循环。如果每个 div 中只有 2 个图像,我开始使用的这段代码可以无缝运行。
图像随机淡入淡出;但是,我需要的功能不仅仅是触发器效果。简而言之,我需要为每个 div 创建一个旋转图像数组,然后编写一个函数来随机选择一个,关闭该数组中的任何可见图像,然后淡入所选图像。
我一遍又一遍地检查了这一点,发现如果图像以列表格式布局,则代码可以工作,但是在响应浏览器窗口大小时,我需要图像浮动和换行。任何帮助(和解释)将不胜感激。
谢谢!
整个小提琴的链接如下,但第一个(5 个)div 如下所示:
<div class="rotator">
<img src="http://www.fourtownfair.com/images/sponsors/agway.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/robertrookey.png" class="rotator-image"/>
<img src="http://www.fourtownfair.com/images/sponsors/fairviewfarms.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/redrobin.png" class="rotator-image" />
</div>
<div class="rotator">
<img src="http://www.fourtownfair.com/images/sponsors/equestriancollection.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/salmonbrook.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/smyth.png" class="rotator-image" />
<img src="http://www.fourtownfair.com/images/sponsors/conlinfarm.png" class="rotator-image" />
</div>
Javascript:
$(function() {
//Timeout are called once and only once, you need to use Interval to repeat the call :-)
$(document).ready( function() {
//Interval with millisecond delay, 2000 = every 2 seconds, always divide by 1000 to get the time.
setInterval(function(){rotateImages();}, 2000);
});
//Breaking this function out, to make the interval statement more readable
var rotateImages = function() {
//Another thing I do to enhance readability, break the collection into a variable
var rotatorArray = $(".rotator");
//We've got the array of rotator blocks, select a random one by length (out of 5 in this case)
var rand = Math.floor(Math.random() * rotatorArray.length);
//If the topmost randomly selected image is hidden, fade in, if it's visible, fade out
if($(rotatorArray[rand].children[0]).css('display') == "none")
{
$(rotatorArray[rand]).children(".rotator-image").fadeIn();
}
else
{
$(rotatorArray[rand]).children(".rotator-image").fadeOut();
}
};
});
在这里小提琴:http: //jsfiddle.net/amandabeau/8Y7NM/5/