具有相同阵列的多个图像旋转器

时间:2014-12-03 02:20:45

标签: jquery arrays

基本上我制作了一个图像旋转器来循环遍历像这样的图像

var home = new Array ('img/hex_portal.png', 'img/hex_guys.png', 'img/hex_aggames.png');
var index = 1;

function rotateImage()
{
  $('#hexOne').fadeOut('slow', function() 
  {
    $(this).attr('src', home[index]);

    $(this).fadeIn('slow', function() 
    {
      if (index == home.length-1)
      {
        index = 0;
      }
      else
      {
        index++;
      }
    });
  });
} 

$(document).ready(function()
{
  setInterval (rotateImage, 3500);
});

它完美地将图像从我的主图像#hexOne中循环出来。现在我想添加另一个占位符,比如hexTwo,以循环显示相同的图像数组,但顺序不同。意思是如果hexOne进入图像1,图像2,图像3,则hexTwo具有完全不同的顺序和速度。有没有办法在不创建全新函数(rotateImage2)的情况下执行此操作,还是应该使用新索引和数组执行此操作?

2 个答案:

答案 0 :(得分:0)

你的意思是每张图片消失的速度吗?为了能够改变这样的速度,你可以将speed定义为rotateImage的参数,并在定义fadeOut或fadeIn的速度时使用它。然后要更改顺序,您可以使用shuffle函数来重新排列初始图像数组:

function shuffle(o){
    for(var j, x, i = o.length; i; j = Math.floor(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
    return o;
};

var home = new Array ('img/hex_portal.png', 'img/hex_guys.png', 'img/hex_aggames.png');
var home2 = shuffle(home);
var index = 1;

function rotateImage(i_speed,o_home,s_id)
{
  $(s_id).fadeOut(i_speed, function() 
  {
    $(this).attr('src', o_home[index]);

    $(this).fadeIn(i_speed, function() 
    {
      if (index == o_home.length-1)
      {
        index = 0;
      }
      else
      {
        index++;
      }
    });
  });
} 

调用rotateImage时,将速度作为整数参数传递,将home或home2作为图像数组传递

答案 1 :(得分:0)

我添加了JSFiddle可能更高级,但这是一个很好的模式。主要对象ImageSwitcher可以使用不同的参数进行初始化,以帮助您实现所需的目标。该对象可以以您想要的任何方式进行扩展,但我认为它可以为您提供充分的控制。

查看我的评论,了解每个部分的含义。图像在不同时间发生变化的原因是,在调用旋转功能之前,它们在完成衰落后等待一段时间。 fadeOut最短的图像当然会先开始。