在Javascript中将随机选择的类添加到相同ID的div中

时间:2017-06-02 18:19:55

标签: javascript jquery

编辑: codepen.io/TechTime/pen/ZKdxQK这是我的项目。正如你可以看到的每个类一个div做动画。我想让所有div从列表中做动画。就像在这里,我的代码试图给每个div一个唯一的类。我想要它,以便一些div可以拥有相同的类,因此都可以接收动画。

我希望有一个类列表,其中一个是随机选择的,然后将其分配给具有相同id的许多div中的一个。

到目前为止,我已经能够实现它,它将类提供给其中一个div,但如果x类在列表中,则只有x divs获得一个类。

我有比课更多的div。我该如何解决我的问题?

到目前为止,我的代码如下:

$(document).ready(function() {
  var klasses2 = [

    "animated bounce",
"animated flash",
"animated pulse",
"animated rubberBand",
"animated shake",
"animated headShake",
"animated swing",
"animated tada",
"animated wobble",
"animated jello",
"animated bounceIn",
"animated bounceInDown",
"animated bounceInLeft",
"animated bounceInRight",
"animated bounceInUp",
"animated bounceOut",
"animated bounceOutDown",
"animated bounceOutLeft",
"animated bounceOutRight",
"animated bounceOutUp",
"animated fadeIn",
"animated fadeInDown",
"animated fadeInDownBig",
"animated fadeInLeft",
"animated fadeInLeftBig",
"animated fadeInRight",
"animated fadeInRightBig",
"animated fadeInUp",
"animated fadeInUpBig",
"animated fadeOut",
"animated fadeOutDown",
"animated fadeOutDownBig",
"animated fadeOutLeft",
"animated fadeOutLeftBig",
"animated fadeOutRight",
"animated fadeOutRightBig",
"animated fadeOutUp",
"animated fadeOutUpBig",
"animated flipInX",
"animated flipInY",
"animated flipOutX",
"animated flipOutY",
"animated lightSpeedIn",
"animated lightSpeedOut",
"animated rotateIn",
"animated rotateInDownLeft",
"animated rotateInDownRight",
"animated rotateInUpLeft",
"animated rotateInUpRight",
"animated rotateOut",
"animated rotateOutDownLeft",
"animated rotateOutDownRight",
"animated rotateOutUpLeft",
"animated rotateOutUpRight",
"animated hinge",
"animated jackInTheBox",
"animated rollIn",
"animated rollOut",
"animated zoomIn",
"animated zoomInDown",
"animated zoomInLeft",
"animated zoomInRight",
"animated zoomInUp",
"animated zoomOut",
"animated zoomOutDown",
"animated zoomOutLeft",
"animated zoomOutRight",
"animated zoomOutUp",
"animated slideInDown",
"animated slideInLeft",
"animated slideInRight",
"animated slideInUp",
"animated slideOutDown",
"animated slideOutLeft",
"animated slideOutRight",
"animated slideOutUp",

  ];
  klasses2.sort(randOrd);
  $("#zewrapper #tris").each(function(i, val) {
    $(this).addClass(klasses2[i]);
  });
});

1 个答案:

答案 0 :(得分:1)

总结评论:

您需要从选择ID更改为选择类

不是对所有div(非正统)使用相同的id,而是可以使用相同的类并更改选择器,例如。 $("#zewrapper .tris")

再次使用该集合中的相同类

您可以将klasses2[i]替换为:

  • klasses2[i % klasses2.length]如果您想保留订单
  • klasses2[Math.floor(Math.random() * klasses2.length)]如果你想随机