An infinite carousel with vanilla JavaScript

吃可爱长大的小学妹 提交于 2019-12-20 10:48:42

问题


I am trying to build my own carousel with pure JavaScript.

I'm struggling with picking up the most efficient way to add an infinite carousel option.

For some reasons, every element (photo, generic object) must have an id

The algorithm I see goes like that:

  • You check if the carousel is overflown (the are enough objects to fit the whole container)
  • If not: append to the back a copy of the first element, then a copy of the second element and so on. (But there will be an issue with the ids, because this object will have the same id)

- If the user is scrolling to the last object (to right) then append the first DOM object to the array back
- If the user is scrolling to the first object (to left) then add the last DOM child to array front.

Is this going to work? Is there any other efficient way of doing an infinite carousel?

I have also heard that it's better to use translate property rather than changing the left, right properties, so it there would be more work for the GPU than for CPU.


回答1:


I created a simple slider with css transformations as the animation technique and plain Javascript.

var img = document.getElementsByClassName("img")[0]; 
img.style.transform = 'translate('+value+'px)';

You can test it in this codepen snippet. http://codepen.io/TobiObeck/pen/QKpaBr

A press on a button translates all images in the respective direction along the x-axis. An image on the edge, is set transparent outerImg.style.opacity = '0'; and translated to the other side. You can add or remove image elements in HTML and it still works.

In this second codepen snippet you can see how it works. The opacity is set to 0.5 so it is observable which image switches the side. Because overflow: hidden is removed, you can see how the images on the edge enqueue on the other side. http://codepen.io/TobiObeck/pen/WGpdLE

Moreover it is notworthy that it is checked wether the animation is complete, otherwise the simultaneously added translations would look odd. Therefore a click won't trigger another animation until unless the animation is completed.

img.addEventListener("transitionend", transitionCompleted, true);

var transitionCompleted = function(){
    translationComplete = true;
}

leftBtnCLicked(){
    if(translationComplete === true){
       //doAnimation
    }
}


来源:https://stackoverflow.com/questions/39673540/an-infinite-carousel-with-vanilla-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!