我在写一组特定的函数时遇到了问题。我正在为响应式网站设计视觉赞助商栏。我有大约20个赞助商标志,分为5个div,我需要随机循环。如果每个div只有2个图像,我已经开始使用的代码无缝工作。轻量级函数使图像数组随机循环?
图像随机淡入和淡出;然而,我需要的功能不仅仅是一个触发器效果。简而言之,我需要为每个div创建一个旋转图像阵列,然后编写一个函数随机选择一个,将该阵列中的任何可见像素都关闭,然后淡入所选图像。
I我总结了这一点,并发现如果图像以列表格式进行布局时可以使用的代码,但是在响应浏览器窗口大小时,我需要图像浮动和换行。任何帮助(和解释)将不胜感激。
谢谢!
链接到整个小提琴低于,但第(5)申报单是这样的:
<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/
我们都犯了同样的错误,我们使用Math.round而不是Math.floor。这导致了一个问题,它试图加载一个图像,甚至没有(4图像索引0,1,2,3,而Math.round可能会返回4) –
@JonasGrumann哎呀,好点! –