Tell me please. How to implement a class change scheme.

  1. motionGoingAnim is a class repository.
  2. The enemy is the object on which the classes are hung.

With this code, all classes are hung on the element, and you need to make a replacement for the next one. That is, alternately, starting from 0 to motionGoingAnim.lenght (icon1 => icon2 => icon3 => icon1 => icon2 ...) At the same time, the previous class must be removed.
icon is the character model in svg . In css set background-image . If there is any better way I would appreciate it.

var motionGoingAnim = ['icon_01','icon_02','icon_03']; if (numberAnim === motionGoingAnim.length) { numberAnim = 0; } else { enemy.addClass(motionGoingAnim[numberAnim]); numberAnim++; } 
  • enemy.removeClass(motionGoingAnim[numberAnim-1]).addClass(motionGoingAnim[numberAnim]); - MasterAlex

1 answer 1

Try this varaint:

 var enemy = $('#enemy'); var motionGoingAnim = ['icon_01', 'icon_02', 'icon_03']; var numberAnim = 0; changeIcon(); function changeIcon() { if (numberAnim == motionGoingAnim.length) { enemy.removeClass(motionGoingAnim[numberAnim - 1]).addClass(motionGoingAnim[0]); numberAnim = 0; } else { enemy.removeClass(motionGoingAnim[numberAnim - 1]).addClass(motionGoingAnim[numberAnim]); } numberAnim++; setTimeout(changeIcon, 1000); } 
 #enemy { width: 100px; height: 100px; transition: background 0.7s ease; } .icon_01 { background-color: red; } .icon_02 { background-color: green; } .icon_03 { background-color: blue; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="enemy"></div> 

UPD. Added transition.

  • lucky что removeClass(undefined) doesn't do anything, it doesn't fall - Grundy
  • thank. removeClass (undefined) I thought it would fall, it was necessary to check. This is what you need. Thanks again very much - HelpaMnePlz
  • In general, which method is more correct for svg animation? I'll try to figure it out myself. Raster images can be with background position, but what about the vector? - HelpaMnePlz
  • @Grundy, in jQuery it is often the case that the code tries to remove classes that an element does not have, for example, when you need to delete a class from some elements of the collection, not knowing which ones. Therefore, I did not consider it necessary to do another if to handle this option. - MasterAlex
  • @HelpaMnePlz, if you do not do the animation path , then svg is no different from png. For a smooth animation, you can add a transition . Added it to the example. - MasterAlex