我在编写一组特定的函数时遇到了问题。我正在为一个响应网站做一个视觉赞助商栏。我有大约20个赞助商标志,分为5个div,我需要随机循环。如果每个分区中只有2个图像,那么我开始使用的这段代码可以无缝工作
图像会随机淡入和淡出;然而,我需要的功能不仅仅是触发器效果。简而言之,我需要为每个div创建一个旋转器图像阵列,然后编写一个函数来随机选择一个,关闭该阵列中的任何可见图像,然后将所选图像淡入。
我已经仔细研究了一遍,发现如果图像以列表格式排列,代码是有效的,但我需要图像在响应浏览器窗口大小时浮动和换行。任何帮助(和解释)都将不胜感激。
谢谢!
下面是整个fiddle的链接,但第一个(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();
}
};
});
Fiddle here:http://jsfiddle.net/amandabeau/8Y7NM/5/
我想你想得太多了(如果我理解正确的话)你能不能不这么做:http://jsfiddle.net/3tEJA/
function animate() {
var max = $(".rotator img").length;
$(".rotator img").eq(Math.floor(Math.random()*max)).fadeIn(1000).delay(2000).fadeOut(1000,function() {
animate();
});
}
animate();
function changeImages() {
$('.rotator').each(function() {
var currentImages = $(this).find('img')
var number = Math.round(Math.random() * currentImages.length());
currentImages.addClass('hidden');
currentImages.eq(number).removeClass('hidden');
});
}
然后可以使用css3转换来获得转换效果,例如:
.rotator img {
opacity: 1
transition: opacity 500ms ease;
}
.rotator img.hidden {
opacity: 0
}
这意味着在页面加载中,除了一个应用了"隐藏"类之外,其他所有图像都被加载。
我还没有测试过,但我很有信心它会起作用。我建议您使用css3过渡而不是animate方法,因为它更具性能。在旧的浏览器上,你仍然会看到图像发生变化,你只会失去褪色的东西