Nth-child CSS-based image rotation

I was able to write a JavaScript carousel and thought it might be more compact to use CSS transitions with nth-child selectors as follows:

 img { transition: all 1s linear; /* or corresponding vendor prefixes */ position:absolute; } img:nth-child(1) { top: 0%; left: 0%; } img:nth-child(2) { top: 0%; left: 50%; } /*and so on...*/ 

Then the elements will be rotated by adding the first child or adding the last child of the container:

 parent.appendChild(parent.children[0]); 

This approach works well for everyone except the item added. It is completely removed and then reattached, so it gets to the right place, but does not use the transition effect. Is there a way to use CSS transitions even when moving an element in the DOM?

jsFiddle Demo - Click a document to promote images.

+4
source share
3 answers

I ended up using the data-* attribute and a selector. This is a bit more verbose than nth-child , but has the advantage of working. It is also cleaner than parsing through class lists.

Each element has a data-order attribute, which can be assigned HTML or JavaScript:

 <img src="http://placekitten.com/203/203" data-order=0 /> 

Replace nth-child with an attribute selector:

 img[data-order="1"] { top: 0%; left: 50%; } 

When rotating, increase the order in the dataset . This seems to update the attribute, although we are modifying the property:

 var forEach = [].forEach, nodes = document.body.children, length = nodes.length; //On rotate: forEach.call(nodes, function(node) { node.dataset.order++; node.dataset.order %= length; }); 

Here is the final result .

0
source

What you can do is add or remove the class name from the element. For example, you have a div element. And its class value is class="item" . If you add another class name with animation to the list of names of this class, this div element will immediately show this animation.

eg. div.className += " animatedClass";

+1
source

A very interesting problem. And here is the solution I came up with. Adds some markup and some CSS, but does it when using nth-child . Honestly, I can work on this a bit later and see if I can come up with a more elegant solution, but so far I have rejected jsFiddle .

The core of this is to switch a class to a wrapper div and use this to rotate styles.

However, as far as your real question is, can you animate the addition of an image, you can, but not in the way you think here. This will be the initial append animation, which will mean when the first page is loaded. You can do this using @keyframes and set it so that the image you want is in place from the starting position where it will be. But, again, this will happen at the first load. You can fake it by "rotating in place" for the first boot. So, all images rotate once upon loading.

+1
source

Source: https://habr.com/ru/post/1388987/


All Articles